gridview嵌套DropDownList選定值

aspx:
<asp:TemplateField HeaderText="狀態" SortExpression="state">
<ItemStyle ForeColor="Gray" />
<ItemTemplate>
<asp:Label ID="labstate" runat="server" Text='<%# (Eval("state").ToString() == "0") ? "已體檢" : "已合格"%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdstate" runat="server" Value='<%# Eval("state") %>' />
<asp:DropDownList ID="ddlstate" runat="server">
<asp:ListItem Value="0">已體檢</asp:ListItem>
<asp:ListItem Value="1">不合格</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
cs:
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1)
{
int orderID = this.myGridView.PageIndex * this.myGridView.PageSize + e.Row.RowIndex + 1;
e.Row.Cells[0].Text = orderID.ToString();
}

 

if (((DropDownList)e.Row.FindControl("ddlstate")) != null)
{
DropDownList ddlstate = (DropDownList)e.Row.FindControl("ddlstate");
//ddlstate.SelectedValue = ((HiddenField)e.Row.FindControl("hdstate")).Value;
//ddlstate.Items.FindByValue(((HiddenField)e.Row.FindControl("hdstate")).Value).Selected = true;
SetSelectedItem(ddlstate, ((HiddenField)e.Row.FindControl("hdstate")).Value);
}
}
private void SetSelectedItem(ListControl list, String value)
{
foreach (ListItem e in list.Items)
if (e.Value == value)
{
e.Selected = true;
return;
}
else
e.Selected = false;
}

你可能感兴趣的:(GridView)