如何将所选值置于DropDownList的顶部?

时间:2012-03-18 14:52:20

标签: c# asp.net sql

  

可能重复:
  How to save in the dropdown the value choosed?

我有一个GridView和一个DropDownList而不是TextBox的列。下拉列表有2个值(1.No,2.Yes)。

问题是,我只能选择“是”的值。后面的代码适用于yes,我也添加了值No。

另一件事是如果我选择一个值(例如“是”),我怎样才能将它带到DropDownList的顶部,因为它总是显示默认值(值为“否”) )。

1 个答案:

答案 0 :(得分:1)

<强> HTML

 <!--Add other attributes as you need to the grid view-->
 <!--NOTE: **OnRowDataBound="GridView_RowDataBound"** -->
 <asp:GridView ID="GridView1" runat="server" 
       OnRowDataBound="GridView1_RowDataBound">
 <Columns>

   <asp:TemplateField HeaderText="Dropdown Column">
       <ItemTemplate>
          <asp:DropDownList ID="ddlYesNo" runat="server">
              <asp:ListItem Value="1" Text="No"></asp:ListItem>
              <asp:ListItem Value="2" Text="Yes"></asp:ListItem>
          </asp:DropDownList>
       </ItemTemplate>
   </asp:TemplateField>
   <!-- OTHER COLUMNS -->
 </Columns>
 <!-- REST OF THE STUFF -->

代码背后

 protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
 {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddl = (DropDownList)e.Row.FindControl("ddlYesNo");
        ddl.SelectedValue = 
          ((System.Data.DataRowView)e.Row.DataItem) ["dataColName"].ToString();

    }
 }