我必須在我的網格視圖中添加一個下拉列表並與數據庫綁定。如何在gridview中添加下拉菜單並將下拉菜單與數據庫綁定?
代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet1TableAdapters.emplTableTableAdapter tb;
tb = new DataSet1TableAdapters.emplTableTableAdapter();
DataTable dt = new DataTable();
dt = tb.GetEmpID();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "empId";
DropDownList1.DataValueField = "empId";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select Employee ID--", ""));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.emplTableTableAdapter tb;
tb = new DataSet1TableAdapters.emplTableTableAdapter();
DataTable dt = new DataTable();
dt = tb.GetGrid(int.Parse(DropDownList1.SelectedValue));
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridView1.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
DataSet1TableAdapters.emplTableTableAdapter tb;
tb = new DataSet1TableAdapters.emplTableTableAdapter();
DataTable dt = new DataTable();
dt = tb.GetGrid(int.Parse(DropDownList1.SelectedValue));
GridView1.DataSource = dt;
GridView1.DataBind();
}
ASPX:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:BoundField DataField="empId" HeaderText="Employee ID" ReadOnly="True" SortExpression="empId" />
<asp:BoundField DataField="empName" HeaderText="Employee Name" ReadOnly="True"
SortExpression="empName" />
<asp:TemplateField HeaderText="Employee Designation" SortExpression="empDesig">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("empDesig") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
表:
現在我越來越喜歡輸出如下:
我需要綁定下拉與DB empDesig列。下面給出了我期望的輸出樣本設計。
http://www.aspsnippets.com/Articles/Populate-DropDownList-with-選擇-價值在-EditItemTemplate中-的-GridView控件功能於ASPNet.aspx – Manoj 2014-11-01 12:14:15