[英]How to change combobox in item template with respect to the data coming from code behind or data source in DataGrid
I have a data grid, and data is coming from database, it has combo boxes in status and I want them to be according to their respective values, for example, there is a column of status, it has a combo box: Open and Close, I want it to be changed with respect to the value it has in database table-column, if it has Close written in database table column, combo box should be selected as Close, if it has Open then it should be selected as Open. 我有一个数据网格,数据来自数据库,它的状态为组合框,我希望它们根据各自的值显示,例如,有一列状态,它有一个组合框:打开和关闭,我希望相对于它在数据库表列中的值进行更改,如果在数据库表列中写入了“关闭”,则组合框应选择为“关闭”,如果它具有“打开”,则应将其选择为“打开”。 Please see the image attached.
请参阅所附图片。
Thanks for Help in advance.
预先感谢您的帮助。
Assuming that you're using a template column, you can do this: 假设您正在使用模板列,则可以执行以下操作:
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("DropDownValueColumn") %>' />
</ItemTemplate>
</asp:TemplateColumn>
If you want to set the SelectedValue in the ItemDataBound
event, you can do it like this: 如果要在
ItemDataBound
事件中设置SelectedValue,可以这样做:
protected void DataGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
DropDownList ddl = e.Item.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
ddl.SelectedValue = DataBinder.Eval(e.Item.DataItem, "DropDownColumnValue").ToString();
}
}
First of all save your data source in viewstate. 首先,将数据源保存在viewstate中。 If datasource is datatable then do like this.
如果数据源是数据表,则这样做。
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlList = (DropDownList)e.Row.FindControl("Name_of_DPList");
int i=e.Row.RowIndex;
DataTable dtTable = (DataTable)ViewState["dtPurchaseOrder"];
string str = dtTable.Rows[i]["Name_Of_column"].ToString();//Name of the column in data source that stores the status.
ddlList.items.FindByText(str).Selected=true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.