关于GridView中DropDownList的问题.
使用Show Smart Tag ,生成了编辑,删除按钮.
又后模板列上添加了一个DropDownList...
1.初始化DropDownList,所有项都加载上,但是默认的是显示数据库中字段的值.
(写在RowCreate中应该没错吧,应该如何去写?)
2.点击更新的时候,(Show Smart Tag) 想连这个DropDownList的值一块更新了,应该怎么去改?
------解决方案--------------------1.写在RowDataBound事件中
2.重新绑定一次就可以了。
------解决方案--------------------//.aspx 填加模版列 注意默认为不能修改,编辑之后才能修改
<asp:TemplateField HeaderText= "state " SortExpression= "state ">
<ItemTemplate>
<asp:DropDownList ID= "DropDownList1 " runat= "server " Enabled= "false "/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID= "DropDownList2 " runat= "server " Enabled= "true "/>
</EditItemTemplate>
//.aspx
添加一个填充数据的方法
private DataTable BindDropDownList()
{
SqlConnection cn = new SqlConnection(@ "server=.\SQLExpress;uid=sa;pwd=sa;database=pubs ");
SqlDataAdapter da = new SqlDataAdapter( "select distinct state from authors ", cn);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
cn.Close();
return ds.Tables[0];
}
在RowDataBound中进行填充数据处理
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList dropTemp;
string state = ((DataRowView)e.Row.DataItem).Row[ "state "].ToString();
dropTemp = (DropDownList)e.Row.FindControl( "DropDownList1 ");
if (dropTemp != null)
{
dropTemp.Items.Add(new ListItem(state, state));
}
if ((e.Row.RowState & DataControlRowState.Edit) != 0)
{
state = ((DataRowView)e.Row.DataItem).Row[ "state "].ToString();
dropTemp = (DropDownList)e.Row.FindControl( "DropDownList2 ");
if (dropTemp != null)
{
dropTemp.DataSource = BindDropDownList();
dropTemp.DataTextField = "state ";
dropTemp.DataBind();
dropTemp.SelectedIndex = dropTemp.Items.IndexOf(dropTemp.Items.FindByText(state));
}
}
}
//更新处理
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection cn = new SqlConnection(@ "server=.\SQLExpress;uid=sa;pwd=sa;database=pubs ");
SqlCommand cmd = new SqlCommand( "update authors set state = @state where au_id = @au_id ", cn);
cmd.Parameters.Add( "@au_id ", SqlDbType.VarChar, 11).Value = GridView1.DataKeys[e.RowIndex].Value.ToString();
cmd.Parameters.Add( "@state ", SqlDbType.VarChar, 2).Value = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl( "DropDownList2 ")).SelectedItem.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
GridView1.EditIndex = -1;
BindGrid();
}
------解决方案--------------------写在RowDataBound事件中