rawatdeepesh
rawatdeepesh

Reputation: 584

populating DropDownList in a gridview with array elements

I have been trying to Populate a DropDownList in my gridview with array elements . The array consists of the column names from another gridview .The array element seems to get the column names from its source but i can not figure out how to give that to the dropdownlist.Here is my code-:

   public partial class Default2 : System.Web.UI.Page
    {
     protected void Page_Load(object sender, EventArgs e)
    {
    string[] excel = new string[250];
    DataTable dtt = (DataTable)Session["griddata"];  //griddata is the gridview data from another page        
    for (int i = 0; i < dtt.Columns.Count; i++)
    {
        excel[i] = dtt.Columns[i].ColumnName;
    }
    Session["exceldata"] = excel;
    ArrayList mylist= (ArrayList)Session["exceldata"];
    DropDownList drd = (DropDownList)GridView2.FindControl("DrdDatabase");
    drd.DataSource = mylist;
    drd.DataTextField = "GridView";
    drd.DataBind();
    }

Thanks in Advance :)

Upvotes: 1

Views: 1765

Answers (2)

Ashish
Ashish

Reputation: 11

Here is the logic which you can use to populate your dropdownlist. ->

Loop at the array.
{
 For each item in array
   {
    add item to dropdownlist.items
   }
}

Sorry for not providing the exact code as I dont have .net editor at my disposal right now but you can use the logic to implement it.

regards.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could simply loop it and add the ListItems programmatically:

DropDownList drd = (DropDownList)GridView1.FindControl("DrdDatabase");
foreach(string colName in mylist)
    drd.Items.Add(new ListItem( colName ));

However, are you sure that you find your DropDownList via GridView1.FindControl? I assume you get a NullRefernceException there. Then you need to show us where it actually is.

If it is in a TemplateField of the GridView you should use the RowDataBound event:

private ArrayList ExcelData
{
    get {
        object excel = Session["exceldata"];
        if (excel == null) Session["exceldata"] = new ArrayList();
        return (ArrayList)Session["exceldata"];
    }
    set {
        Session["exceldata"] = value;
    }
}

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
        foreach (string colName in ExcelData)
            ddl.Items.Add(new ListItem(colName));
    }
}

Upvotes: 0

Related Questions