一个gridview的DropDownList绑定问题!!!
我在gridview的编辑模板中放了一个DropDownList控件,控件是绑定数据库中的数据,当点击编辑铵钮时显示dropdownlist。数据绑定是实现了,可是在点击gridview中编辑按钮时dropdownlist中默认选中的不是该列的值。在更新时也得不到dropdownlist的selectedvalue值。不知为何,请各位帮看看,谢谢了~代码如下:
<asp:GridView ID="gridMember" runat="server" AllowSorting="True" AutoGenerateColumns="False" Width="75%" DataKeyNames="proID" AllowPaging="True" OnPageIndexChanging="gridMember_PageIndexChanging" OnRowDataBound="gridMember_RowDataBound" OnRowEditing="gridMember_RowEditing" OnRowUpdating="gridMember_RowUpdating" OnRowCancelingEdit="gridMember_RowCancelingEdit">
<Columns>
<asp:TemplateField HeaderText="产品品牌">
<ItemTemplate><%#Eval("brandN")%></ItemTemplate>
<EditItemTemplate>
<asp:HiddenField runat="server" ID="hidtxt" Value='<%#Eval("brandN")%>' />
<asp:DropDownList runat="server" id="drop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
后台代码:
protected void gridMember_RowDataBound(object sender, GridViewRowEventArgs e)
{
string str = "select * from brands";
DataSet dss = new DataSet();
dss = dataFactory.ds(str, dss, "tb");
if (((DropDownList)e.Row.FindControl("drop")) != null)
{
DropDownList drp = (DropDownList)e.Row.FindControl("drop");
// 生成 DropDownList 的值,也可以取得数据库中的数据绑定
drp.DataSource = dss.Tables["tb"];
drp.DataTextField = "brand";
drp.DataValueField = "brandID";
drp.DataBind();
// 选中 DropDownList
drp.SelectedValue = ((HiddenField)e.Row.FindControl("hidtxt")).Value.ToString();
//
}
}
更新代码:
protected void gridMember_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string drp = ((DropDownList)gridMember.Rows[e.RowIndex].FindControl("drop")).SelectedValue;
string str = "update proType set brand=@a1 where proID="+gridMember.DataKeys[e.RowIndex].Value+"";
OleDbCommand cmd = new OleDbCommand(str,conn.connData());
cmd.Parameters.Add("a1", OleDbType.Integer).Value = drp;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
gridMember.EditIndex = -1;
Init();
}