开发者

Problem filling dropdown list of gridview from dataset

I'm using the code below:

protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
    MySqlConnection objMycon1 = new MySqlConnection(strProvider);
    objMycon1.Open();
    MySqlCommand cmd1 = new MySqlCommand("select * from tblcountrynames",objMycon1); 
    MySqlDataAdapter da = new MySqlDataAdapter(cmd1);
    DataSet ds = new DataSet(); 
    da.Fill(ds);
    // DropDownList Control Object Created to bind the data dynamically with each 
    // nested DropDownlist control placed inside the template column of the GridView 
    // Control.
    DropDownList drdList;

    // foreach loop is used to loop through each row of GridView Control.

    foreach (GridViewRow grdRow in grdViewCInfo.Rows)
    {    
        // Nested DropDownList Control reference is passed to the DrdList object.
        // This will allow you access the properties of dropdownlist placed 
        // inside the GridView Template column. 
    开发者_运维技巧    drdList = (DropDownList)(grdViewCInfo.Rows[grdRow.RowIndex].FindControl("ddlCountry" ));  
        // DataBinding of nested DropDownList Control for each row of GridView Control.  
        drdList.DataSource = ds;   
        drdList.DataValueField = "ID"; 
        drdList.DataTextField = "Name";
        drdList.DataBind();
    }
}

It gives an error as:

Object reference not set to an instance of an object.

At the line drdList.DataSource = ds;

How do I fix this???


Try specifying the COLUMN in the following line of code:

drdList = (DropDownList)( grdViewCInfo.Rows[ grdRow.RowIndex ][ColumnIndex].FindControl( "ddlCountry" ));

Another option is to loop through columns in another foreach

More info based on your comment:

Looks like you're new to ASP.NET, that's why I recommend the following:

Use asp:TemplateColumn and put the asp:DropDownList in the EditTemplate. Hook the DropDown up to SqlDataSource (or whatever else datasource you want to use).

The binding will be handled for you.

I can't elaborate any further w/o seeing your ASP.NET code and knowing more about your requirements.


Try This

DropDownList ddl;
        int i = 0;
        foreach (GridViewRow grdrow in grdmenu.Rows)
        {
     ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffer");
     ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["Offer"]);
     ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffers");
     ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["OfferType"]);

            i++;  
            ddl.DataBind();
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜