Search code examples
c#asp.netwebformssqldatasource

selecting dropdownlist item from sqldatamart asp.net


I have 6 dropdownlist that are populated from a sqldatasource. I also have another sqldatasource that returns some rows. What I want to do is to go through each row of the second datasource and select that value in my dropdowns. So if second datasource contains three rows it would select the appropriate value in the first three dropdownlist and set the others to "N/A" for example.

here is some pseudo code I thought of

protected void fileattributes_ItemDataBound(object sender, ListViewItemEventArgs e)
{
        DropDownList kw1 = (DropDownList)e.Item.FindControl("keyw1");
        DropDownList kw2 = (DropDownList)e.Item.FindControl("keyw2");
        DropDownList kw3 = (DropDownList)e.Item.FindControl("keyw3");
        DropDownList kw4 = (DropDownList)e.Item.FindControl("keyw4");
        DropDownList kw5 = (DropDownList)e.Item.FindControl("keyw5");
        DropDownList kw6 = (DropDownList)e.Item.FindControl("keyw6");

        DropDownList[] array = { kw1, kw2, kw3, kw4, kw5, kw6 };

        for(int i = 0; i<sqldatasource2.length;i++)
        {            
              array[i].SelectedItem.Text = sqldatasource2.item    
        }

        foreach(Array a in array)
        {    
              if (a is null)
              {    
                   a.selecteditem.text = "N/A";
              }        
        }        
}    

Solution

  • DataSourceSelectArguments args = new DataSourceSelectArguments();
    DataView view = (DataView)SqlDataSource1.Select(args);
    DataTable dt = view.ToTable();
    
    DropDownList[] array = { kw1, kw2, kw3, kw4, kw5, kw6 };
    int i;
    for (i = 0; i < dt.Rows.Count;i++ )
    {
        array[i].SelectedItem.Text = dt.Rows[i][0].ToString();
    }
    
    // If array length (number of DropDowns) is greater than rows in datasource
    // Remaining Dropdowns will get text N/A --- Now i=dt.Rows.Count
    for (; i < array.Length; i++)
    {
        array[i].SelectedItem.Text = "N/A";
    }