从数据集中填充网格视图的下拉列表时出现问题
本文关键字:下拉列表 问题 视图 数据集 数据 集中 填充 网格 | 更新日期: 2023-09-27 17:57:42
我正在使用以下代码:
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;
我该怎么解决这个问题???
尝试在以下代码行中指定COLUMN:
drdList = (DropDownList)( grdViewCInfo.Rows[ grdRow.RowIndex ][ColumnIndex].FindControl( "ddlCountry" ));
另一种选择是循环通过另一个foreach
中的列
更多信息基于您的评论:
看起来你是ASP.NET的新手,这就是为什么我推荐以下内容:
使用asp:TemplateColumn并将asp:DropDownList放入EditTemplate中。将DropDown连接到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();
}