GridView中绑定DropDownList并用DropDownList显示对应字段数据;
- HeaderTemplateRowDataBound设置GirdView 的 DataKeyNames="Name" 即数据源中的字段,我设置的是:Name;
- 添加GridView事件: RowDataBound
- 在事件事首先判断行的类型是不是数据行;因为第一行通常是 HeaderTemplate;(图中的第一行就是表头,如编号,标识码,商品名称。。。。)
-
在当前行中查换DropDownList的Id;DropDownList ddlInType = e.Row.FindControl("ddlInType") as DropDownList;
设置DropDownList的数据源及绑定的字段;
然后再取出当数据库中的值,与DataKeys绑定;(上面提到的 DataKeyNames="Name")
protected void gvInBillList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlInType = e.Row.FindControl("ddlInType") as DropDownList;
ddlInType.DataSource = new InBillManager().GetDropDownList();
ddlInType.DataValueField = "Id";
ddlInType.DataTextField = "Name";
ddlInType.DataBind();
this.SelectDropDownList(ddlInType, this.gvInBillList.DataKeys[e.Row.RowIndex]["Name"].ToString());
}
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlInType = e.Row.FindControl("ddlInType") as DropDownList;
ddlInType.DataSource = new InBillManager().GetDropDownList();
ddlInType.DataValueField = "Id";
ddlInType.DataTextField = "Name";
ddlInType.DataBind();
this.SelectDropDownList(ddlInType, this.gvInBillList.DataKeys[e.Row.RowIndex]["Name"].ToString());
}
}
public void SelectDropDownList(DropDownList objDropDownList, string valueOrText)
{
objDropDownList.ClearSelection();
ListItem objLI = objDropDownList.Items.FindByValue(valueOrText);
if (objLI == null)
{
objLI = objDropDownList.Items.FindByText(valueOrText);
}
if (objLI != null)
{
objDropDownList.ClearSelection();
objLI.Selected = true;
}
{
objDropDownList.ClearSelection();
ListItem objLI = objDropDownList.Items.FindByValue(valueOrText);
if (objLI == null)
{
objLI = objDropDownList.Items.FindByText(valueOrText);
}
if (objLI != null)
{
objDropDownList.ClearSelection();
objLI.Selected = true;
}
}