2011-05-19 32 views
3

我想在用户编辑行时在我的GridView中以DropDownList的形式显示一个字段。 DropDownList将预填充两个值,“是”和“否”,并根据用户选择的值我想设置一个变量。编辑GridView时的显示下拉列表

例如:

我有一个名为active的字段。 1 =有效,0 =未激活。虽然对于用户,我希望他们将Active设置为“是”(1)或“否”(0)。当编辑一行时,他们可以从下拉列表中选择“是”或“否”,它会将变量设置为1或0,这样我就可以将它发回SQL更新。

我发现这个MSDN article

但它只告诉我如何从DataSource填充DropDownList,这对我不起作用,因为每个字段对于活动都有yes或no。即使只是在查看GridView时,它也会显示下拉菜单,而不仅仅是在编辑时。

我希望这是有道理的,谢谢你的帮助。

编辑

这里是我现在的代码,它几乎就像我想它。现在我需要做的就是如果Active的值为“True”,则将标签文本更改为“Yes”,如果Active的值为“False”,则将标签文本更改为“No”。

<asp:TemplateField HeaderText="Active" SortExpression="Active" > 
         <ItemTemplate> 
          <asp:Label ID="lblActive" runat="server" text='<%# Eval("Active") %>'/> 
         </ItemTemplate> 
         <EditItemTemplate> 
          <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Active") %>'> 
           <asp:ListItem Text="Yes" Value="True"></asp:ListItem> 
           <asp:ListItem Text="No" Value="False"></asp:ListItem> 
          </asp:DropDownList> 
         </EditItemTemplate> 
        </asp:TemplateField> 
+0

感谢所有的回复。我还有一个问题,请参阅上文。 – Will 2011-05-23 13:47:17

+0

我将Eval值传递给后面代码中的方法来解决问题。 – Will 2011-05-24 13:44:03

回答

1

您可以添加列表项喜欢...

<asp:DropDownList ID="DropDownList1" runat="server"> 
     <asp:ListItem Text="Yes" Value="1"></asp:ListItem> 
     <asp:ListItem Text="No" Value="0"></asp:ListItem> 
    </asp:DropDownList> 

而且可以绑定SelectedValue,它会自动通过DB一个1 or o

+0

如果我只是想让用户设置活动值,但我需要拉取当前值为活动状态,然后在GridView的“编辑”模式下通过下拉菜单更改该值,则这可行。 – Will 2011-05-19 14:51:06

+0

这就是SelectedValue属性为你所做的绑定。 – Jamie 2011-05-19 15:50:28

0

使用在EditTemplate下拉列表,并使用标签来显示ItemTemplate 选择参阅在msdn post这个例子(一路滚动到年底下拉列表的情况)。

0
  1. 放置一个标签控制(显示在数据库中的电流值)和下拉列表中edititem模板

    <asp:Label ID="lbl" runat="server" Text='<%#Eval("authostatus") %>' Visible="false"></asp:Label> 
    <asp:DropDownList ID="Autharisationddl" runat="server"> 
        <asp:ListItem Text="Yes" Value="1"></asp:ListItem> 
        <asp:ListItem Text="No" Value="0"></asp:ListItem> 
    </asp:DropDownList> 
    
  2. 在gridview的RowDataBound事件根据标签控制值设置下拉值。

    if ((e.Row.RowState & DataControlRowState.Edit) > 0) 
    { 
        Label lbl= (Label)e.Row.FindControl("lbl"); 
        DropDownList ddl= (DropDownList)e.Row.FindControl("ddl"); 
    
        if (lbl!= null) 
        { 
        if (lbl.Text == "1") 
         ddl.SelectedValue = "1"; 
        else if (lbl.Text == "0") 
         ddl.SelectedValue = "0"; 
        } 
    } 
    

感谢

+0

这很有帮助,但我想根据从SQL查询中获得的值来设置标签。看我的编辑到我原来​​的帖子。 – Will 2011-05-23 13:48:18

0

你不需要的RowDataBound,只是需要你的列转换成一个模板字段。

0

这是迟到的回复,但它会帮助其他人遇到相同的情况。

codezone4 tutorial