C# 从数据集中填充gridview下拉列表时出现问题
我正在使用下面的代码:C# 从数据集中填充gridview下拉列表时出现问题,c#,dataset,C#,Dataset,我正在使用下面的代码: protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e) { MySqlConnection objMycon1 = new MySqlConnection(strProvider); objMycon1.Open(); MySqlCommand cmd1 = new MySqlCommand("select * from tblcountryna
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行代码>
如何解决此问题?尝试在以下代码行中指定列:
drdList = (DropDownList)( grdViewCInfo.Rows[ grdRow.RowIndex ][ColumnIndex].FindControl( "ddlCountry" ));
另一个选项是在另一个foreach
更多信息基于您的评论:
看起来您是ASP.NET新手,这就是我推荐以下内容的原因:
使用asp:TemplateColumn并将asp:DropDownList放入EditTemplate。将下拉列表连接到SqlDataSource(或您想要使用的任何其他数据源)
绑定将为您处理
我看不到你的ASP.NET代码,也不了解你的需求,所以我不能再详细说明了。试试这个
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();
}
我包含列索引,因此错误消失,但在编辑事件时下拉列表显示为空。它不会进入循环,因为我跟踪了它。如果它没有进入循环,您是如何在drdList.DataSource=ds;处获得NullReferenceException的?因为当时我没有指定它命中那行代码这一事实意味着它进入了循环,不管它是否抛出异常都无关紧要