【问题标题】:Gridview row editing - dynamic binding to a DropDownListGridview 行编辑 - 动态绑定到 DropDownList
【发布时间】:2010-10-24 10:13:27
【问题描述】:

我正在尝试让 ASP.NET 3.5 GridView 在显示时将所选值显示为字符串,并显示 DropDownList 以允许我在编辑时从给定的选项列表中选择一个值。看起来很简单?

我的网格视图看起来像这样(简化):

<asp:GridView ID="grvSecondaryLocations" runat="server" 
              DataKeyNames="ID" OnInit="grvSecondaryLocations_Init" 
              OnRowCommand="grvSecondaryLocations_RowCommand" 
              OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
              OnRowDeleting="grvSecondaryLocations_RowDeleting"
              OnRowEditing="grvSecondaryLocations_RowEditing" 
              OnRowUpdating="grvSecondaryLocations_RowUpdating"  >
<Columns>
    <asp:TemplateField>
         <ItemTemplate>
              <asp:Label ID="lblPbxTypeCaption" runat="server" 
                                 Text='<%# Eval("PBXTypeCaptionValue") %>' />
         </ItemTemplate>
         <EditItemTemplate>
                      <asp:DropDownList ID="ddlPBXTypeNS" runat="server" 
                               Width="200px" 
                               DataTextField="CaptionValue" 
                               DataValueField="OID" />
         </EditItemTemplate>
    </asp:TemplateField>
</asp:GridView>

网格在不处于编辑模式时显示正常 - 所选 PBX 类型在 asp:Label 控件中显示其值。这并不奇怪。

我将 DropDownList 的值列表加载到表单的 OnLoad 事件中名为 _pbxTypes 的本地成员中。我验证了这一点 - 它有效,值在那里。

现在我的挑战是:当网格进入特定行的编辑模式时,我需要绑定存储在_pbxTypes 中的 PBX 列表。

很简单,我想 - 只需在 RowEditing 事件中抓取下拉列表对象并附加列表:

protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
    grvSecondaryLocations.EditIndex = e.NewEditIndex;

    GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];

    DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
    if (ddlPbx != null)
    {
        ddlPbx.DataSource = _pbxTypes;
        ddlPbx.DataBind();
    }

    .... (more stuff)
}

问题是 - 我从来没有从 FindControl 电话中得到任何回报 - 似乎 ddlPBXTypeNS 不存在(或找不到)。

我错过了什么?一定是真的很愚蠢....但到目前为止,我所有的谷歌搜索、阅读 GridView 控件和询问朋友都没有帮助。

谁能发现缺失的链接? ;-)

【问题讨论】:

    标签: asp.net gridview drop-down-menu dynamic-binding


    【解决方案1】:

    很简单...你做错了,因为在那个事件中控件不存在:

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && 
            (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        { 
            // Here you will get the Control you need like:
            DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
        }
    }
    

    也就是说,它只对DataRow(实际包含数据的行)有效,并且如果它处于编辑模式...因为您一次只能编辑一行。 e.Row.FindControl("ddlPBXTypeNS") 只会找到您想要的控件。

    【讨论】:

    • Tricky.... 我得到了这个事件,但是 RowState 是“Alternate | Edit” - 所以你的 IF 永远不会是真的 :-)
    • 好的,我更改了您的 if 以检查是否设置了“编辑”位(忽略可能设置的任何其他位),现在它就像一个魅力!非常感谢!
    • 我实际上将其更改为:(e.Row.RowState &amp; DataControlRowState.Edit) == DataControlRowState.Edit,以便过滤掉“编辑”标志,而不考虑可能设置的任何其他标志
    • 有很多方法可以完成同样的事情:) 但我更喜欢你的想法,它更干净! ...已编辑;)
    • balexandre 你的回答太棒了!真的帮我解决了类似的问题stackoverflow.com/questions/5169538/gridview-take-a-row 在网上看我找不到任何像你这样的好的代码示例!
    【解决方案2】:

    我在 3.5 中使用 ListView 而不是 GridView。当用户想要编辑时,我已将下拉列表的选定项设置为记录的该列的现有值。我可以访问 ItemDataBound 事件中的下拉列表。代码如下:

    protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        // This stmt is used to execute the code only in case of edit 
        if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
        {
            ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
            ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
        }
    }
    

    【讨论】:

    • 它不是 List 是 gridView!
    • 完全正确 - 我真的不想为了让它工作而改变它,如果可能的话......无论如何谢谢!
    • balexandre ...我已经提到它不是gridview ...这只是一个仅供参考而不是soln ...如果你们学会给-ve点'不正确会更好答案”而不是“其他解决方案或仅供参考”
    【解决方案3】:
    protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        grvSecondaryLocations.EditIndex = e.NewEditIndex;  
    
        DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
        if (ddlPbx != null)  
        {  
            ddlPbx.DataSource = _pbxTypes;  
            ddlPbx.DataBind();  
        }  
    
        .... (more stuff)  
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用 SelectedValue:

      <EditItemTemplate>
          <asp:DropDownList ID="ddlPBXTypeNS"
                            runat="server"
                            Width="200px"
                            DataSourceID="YDS"
                            DataTextField="CaptionValue"
                            DataValueField="OID"
                            SelectedValue='<%# Bind("YourForeignKey") %>' />
          <asp:YourDataSource ID="YDS" ...../>
      </EditItemTemplate>
      

      【讨论】:

      • 这是干净和简单的。为我工作。
      【解决方案5】:

      选中的answer from balexandre 效果很好。但是,如果适应其他一些情况,它会产生问题。

      当我编辑一行时,我使用它来更改两个标签控件的值 - lblEditModifiedBy 和 lblEditModifiedOn,以便在“更新”时将正确的 ModifiedBy 和 ModifiedOn 保存到数据库中。

      当我单击“更新”按钮时,在RowUpdating 事件中它显示了我在OldValues 列表中输入的新值。更新数据库时,我需要真正的“旧值”作为 Original_ 值。 (GridView 附加了一个ObjectDataSource。)

      解决此问题的方法是使用 balexandre 的代码,但在 gv_DataBound 事件中采用修改后的形式:

      protected void gv_DataBound(object sender, EventArgs e)
      {
          foreach (GridViewRow gvr in gv.Rows)
          {
              if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
              {
                  // Here you will get the Control you need like:
                  ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
                  ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
              }
          }
      }
      

      【讨论】:

        【解决方案6】:
         <asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
                    AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
                    BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
                    OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                    OnRowDeleting="GridView1_RowDeleting">
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <Columns>
                    <asp:TemplateField HeaderText="SerialNo">
                    <ItemTemplate>
                    <%# Container .DataItemIndex+1 %>.&nbsp
                    </ItemTemplate>
                    </asp:TemplateField>
                        <asp:TemplateField HeaderText="RollNo">
                            <ItemTemplate>
                                <%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
                                <asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="SName">
                            <ItemTemplate>
                            <%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
                                <asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="C">
                            <ItemTemplate>
                            <%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
                                <asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Cpp">
                            <ItemTemplate>
                            <%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
                               <asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Java">
                            <ItemTemplate>
                               <%--  <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
                                <asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                            <EditItemTemplate>
                                <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
                                    CommandName="Update"></asp:LinkButton>
                                <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
                                    CommandName="Cancel"></asp:LinkButton>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
                                    Text="Edit"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
                        <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
                    </Columns>
                </asp:GridView>
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
                            <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
                            <asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
                            <asp:TextBox ID="txtc" runat="server"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
                            <asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
                            <asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
                            <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
                        </td>
                    </tr>
                </table>
        

        【讨论】:

        • 欢迎使用 StackOverflow:如果您发布代码、XML 或数据示例,请在文本编辑器中突出显示这些行并单击“代码示例”按钮 ({ } ) 在编辑器工具栏上很好地格式化和语法突出显示它!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-01
        • 1970-01-01
        • 2011-09-11
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多