如何将 2 个数据库表绑定到 gridview 和一个作为下拉列表
本文关键字:一个 下拉列表 数据库 绑定 gridview | 更新日期: 2023-09-27 18:36:37
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="301px" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
<%-- <asp:BoundField DataField="StudentDOB" HeaderText="StudentDOB" SortExpression="StudentDOB" />--%>
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/Employee/EmployeeEditPage.aspx?StudentID={0}", Eval("StudentID"))%>'> Edit</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
以上是我的设计:下面我编写了用于显示数据库的代码,该数据库具有表departmenttable
和另一个表studenttable
以将值显示在网格中。在部门表中,我有departmentname(dept_name)
这应该在网格视图中的下拉列表中出现。但它显示错误..请帮忙..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(DataBase.GetConnection());
con.Open();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList = (DropDownList)e.Row.FindControl("dept_name");
//bind dropdownlist
DataTable dt = con.GetData("select dept_name from dbo.DepartmentTable");
ddList.DataSource = dt;
ddList.DataTextField = "dept_name";
ddList.DataValueField = "DeptName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["DeptName"].ToString();
con.Close();
GridView1.DataBind();
}
}
}
要绑定dropdownlist
GriView
,首先需要通过它的id
找到它。在您的示例代码中,您正在尝试查找未dropdownlist
的内容。试试这个,
DropDownList ddList = (e.Row.FindControl("DropDownList1") as DropDownList);
if(ddList != null)
{
//your code
}