GridView中的ASP.NET控件未发现存在于代码后面
我有一个DropDownList,我想用数据库中的列值填充。 但是,当我尝试在后面的代码中绑定DropDownList时,IDE会一直告诉我:
“当前上下文中不存在’EqpCatDDL’这个名称”
我不确定自从我通过其ID引用控件以来发生了什么。 以下是代码:
ASPX:
C#:
public void Populate1() { string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString; SqlConnection connection = new SqlConnection(connString); SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection); cmd.Connection.Open(); SqlDataReader ddlValues; ddlValues = cmd.ExecuteReader(); EqpCatDDL.DataSource = ddlValues; EqpCatDDL.DataValueField = "EqpCateID"; EqpCatDDL.DataTextField = "EqpCat"; EqpCatDDL.DataBind(); cmd.Connection.Close(); cmd.Connection.Dispose(); } protected void Page_Load(object sender, EventArgs e) { Populate1(); }
IDE无法找到EqpCatDDL控件。
我使用以下内容:Visual Studio 2010,Microsoft SQL Server Management Studio 2008
我正在使用Visual Studio网站
使用此代码将数据绑定到dropdown
而不使用RowDataBound
。
创建一个将数据绑定到dropdown
的函数,如下所示,并在Page_Load
事件中调用它
Public void fill_gridView_dropDown() { // your connection and query to retrieve dropdown data will go here // this loop will go through all row in GridView foreach(GridViewRow row in your_gridView_Name.Rows) { DropDownList dropDown = (DropDownList)row.FindControl("dropDownList_id"); dropDown.DataSource = dataSource; dropDown.DataValueField = "ValueField"; dropDown.DataTextField = "TextField"; dropDown.DataBind(); } }
请注意,您必须首先bind
GridView,然后必须绑定您的下拉列表
您的下拉列表是在gridview中,因此您可以尝试使用此代码
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var ddl = (DropDownList)e.Row.FindControl("EqpCatDDL'"); SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); EqpCatDDL.DataSource = ds; EqpCatDDL.DataValueField = "EqpCateID"; EqpCatDDL.DataTextField = "EqpCat"; EqpCatDDL.DataBind(); } }
您不能像这样直接填充GridView's
dropdownlist
。 您需要先设置GridView
数据源,即
GridView1.DataSource = DataSource
如果您想访问此gridview的dropdownlist
,您可以使用GridView
RowDataBound
事件处理程序ie
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //Checking whether the Row is Data Row if (e.Row.RowType == DataControlRowType.DataRow) { //Finding the Dropdown control. Control ctrl = e.Row.FindControl("EqpCatDDL"); if (ctrl != null) { DropDownList dd = ctrl as DropDownList; List lst = new List(); dd.DataSource = lst; dd.DataBind(); } } }