Home > Back-end >  Get the value of the selected item in a dropdownlist (DataSource)
Get the value of the selected item in a dropdownlist (DataSource)

Time:02-12

I just created a dropdownlist and I'm trying to get the value of the selected item in particular the value isActive. This DropDownList is built with a dataTable. How to get the value?

I based myself on the following document : https://docs.microsoft.com/fr-fr/dotnet/api/system.web.ui.webcontrols.dropdownlist?view=netframework-4.8

Thanks in advance.

 if (!PostBack) {

    this.ddlList.DataSource = CreateDataSource(this.List);
    this.ddlList.DataTextField = "Name";
    this.ddlList.DataValueField = "value";
    this.ddlList.DataBind();
 }


 ICollection CreateDataSource(List<Vendor> vendorList)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Value", typeof(string)));
        dt.Columns.Add(new DataColumn("IsActive", typeof(bool)));

        foreach (var item in List)
        {
            dt.Rows.Add(CreateRow(item.DisplayName, item.Value, item.IsActive, dt));
        }
        DataView dv = new DataView(dt);
        return dv;
    }

  
    DataRow CreateRow(string Name, string Value, bool IsActive, DataTable dt)
    {    
        DataRow dr = dt.NewRow();
                    
        dr[0] = Name;
        dr[1] = Value;
        dr[2] = IsActive;

        return dr;
    }

CodePudding user response:

var test = (DataView)this.ddlList.DataSource;
var test2 = test[i].Row["nameOfRow"]; //i is the index of the line 
                             
  • Related