locked
Index Value RRS feed

  • Question

  • User-1499457942 posted

    Hi

      I have below dropdown . I want value not text

    ddlfruits.DataSource = new List<string>() {"","Apple","Banana","Orange"};
    ddlfruits.DataBind();

    Thanks

    Saturday, September 22, 2018 5:12 PM

Answers

  • User-1716253493 posted

    Use listitems as the source or directly add it to ddl.items

            ListItemCollection items = new ListItemCollection();
            items.Add(new ListItem("manggo", "value1"));
            items.Add(new ListItem("Apple", "value2"));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 23, 2018 4:42 AM

All replies

  • User465171450 posted

    Your list is only a string array. There's nothing here that says value or text so the value will become the same as text.

    Saturday, September 22, 2018 7:58 PM
  • User-1716253493 posted

    Use listitems as the source or directly add it to ddl.items

            ListItemCollection items = new ListItemCollection();
            items.Add(new ListItem("manggo", "value1"));
            items.Add(new ListItem("Apple", "value2"));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 23, 2018 4:42 AM
  • User61956409 posted

    Hi JagjitSingh,

    If you check the html markup of your dropdown ddlfruits, you will find it rendered as below, the value and text of dropdown's option with same value.

    If you want populate the value and text of dropdown's options with different value, you can refer to the following sample code.

    var optionlist = new List<string>() { "", "Apple", "Banana", "Orange" };
    
    DataTable dt_for_ddl = new DataTable();
    dt_for_ddl.Columns.Add("ddl_val");
    dt_for_ddl.Columns.Add("ddl_text");
    int index = 0;
    
    foreach (var item in optionlist)
    {
        //your code logic to populate DataTable dt_for_ddl's ddl_val and ddl_text columns
    
        dt_for_ddl.Rows.Add(index, item);
        index++;
    }
    
    ddlfruits.DataSource = dt_for_ddl;
    ddlfruits.DataTextField = "ddl_text";
    ddlfruits.DataValueField = "ddl_val";
    ddlfruits.DataBind();

    With Regards, 

    Fei Han

    Monday, September 24, 2018 5:21 AM