从数据集填写网格视图的下拉列表问题

时间:2011-05-24 05:52:52

标签: c# dataset

我正在使用以下代码:

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();
    }
}

它出现错误:

  

对象引用未设置为对象的实例。

drdList.DataSource = ds;

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试在以下代码行中指定COLUMN:

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

另一种选择是循环浏览另一个foreach

中的列

根据您的评论提供更多信息:

看起来你是ASP.NET新手,这就是我推荐以下内容的原因:

使用asp:TemplateColumn并将asp:DropDownList放在EditTemplate中。将DropDown挂钩到SqlDataSource(或您想要使用的任何其他数据源)。

将为您处理绑定。

我无法详细说明您的ASP.NET代码并了解更多有关您的需求的信息。

答案 1 :(得分:0)

试试这个

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();
        }