简体   繁体   English

动态地将行添加到GridView,其中包含ASP.NET中的Web控件

[英]Dynamically add rows to GridView which contain web controls in ASP.NET

Hi I'm having a great issue because I don't know where to start. 嗨,我遇到了一个很大的问题,因为我不知道从哪里开始。 I need to create a Gridview which has to buttons below it, a "Create Row" button and a "Delete Row" button. 我需要创建一个Gridview,其下方必须具有按钮,“创建行”按钮和“删除行”按钮。 I want that everytime the "Create Row" button is pressed a new row to be added to the GridView, however the main problem is that I need that new row to be filled with different controls such as DropDownLists and TextBox, but I have no idea of how to do it properly. 我希望每次按下“创建行”按钮时都将新行添加到GridView,但是主要问题是我需要用不同的控件(例如DropDownLists和TextBox)填充新行,但是我不知道如何正确地做。 Here is an image of how I want the GridView to be: 这是我想要GridView的图像:

Each row has 2 dropdown lists, two textbox and a button 每行有2个下拉列表,两个文本框和一个按钮 在此处输入图片说明

I know that I need to bind the GridView to a data source such as a dataTable, but I have no idea if that will work with controls such as TextBox or DropDownLists. 我知道我需要将GridView绑定到数据源(例如dataTable),但是我不知道它是否可以与TextBox或DropDownLists等控件一起使用。 Sorry if I don't add any code because I really don't know where to start. 很抱歉,如果我不添加任何代码,因为我真的不知道从哪里开始。 Thank you. 谢谢。

If i understood it right u can follow this: 如果我理解正确,那么您可以遵循以下步骤:

  1. Create Gridview 创建Gridview

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" DataKeyNames="RowNumber"> <Columns> <asp:BoundField DataField="RowNumber" HeaderText="Row Number" Visible="false" /> <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"> <ItemTemplate> <asp:CheckBox runat="server" ID="chkSelect" ToolTip="Select To Delete This Row" /> <asp:Label runat="server" ID="lblId" Text='<%# Bind("Id") %>' Visible="false"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="First Entry"> <ItemTemplate> <asp:Label runat="server" ID="lblFirstEntry" Visible="false" Text='<%# Eval("FirstEntry") %>'></asp:Label> <asp:DropDownList ID="ddlFirstEntry" runat="server" ClientIDMode="Static" CssClass="ddlFirstEntry"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Second Entry"> <ItemTemplate> <asp:Label runat="server" ID="lblSecondEntry" Visible="false" Text='<%# Eval("SecondEntry") %>'></asp:Label> <asp:DropDownList ID="ddlSecondEntry" runat="server" ClientIDMode="Static" CssClass="ddlSecondEntry"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="First Text Box"> <ItemTemplate> <asp:Label runat="server" ID="lblFirstTextBox" Visible="false"></asp:Label> <asp:TextBox ID="txtFirstTextBox" runat="server" Text='<%# Eval("FirstTextBox") %>' CssClass="txtFirstTextBox"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Second Text Box"> <ItemTemplate> <asp:Label runat="server" ID="lblSecondTextBox" Visible="false"></asp:Label> <asp:TextBox ID="txtFSecondTextBox" runat="server" Text='<%# Eval("SecondTextBox") %>' CssClass="txtSecondTextBox"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Second Text Box"> <ItemTemplate> <asp:Button ID="btnSubmit" runat="server" Text="Button" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

  1. Then in Code behind in Page_Load call this method 然后在Page_Load后面的代码中调用此方法

     private void InitializeGrid() { try { ViewState["applicationDetail"] = null; DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("FirstEntry", typeof(string)), new DataColumn("SecondEntry",typeof(string)), new DataColumn("FirstTextBox", typeof(string)), new DataColumn("SecondTextBox", typeof(string)) }); DataRow drRow = dt.NewRow(); drRow["Id"] = 1; drRow["FirstEntry"] = string.Empty; drRow["SecondEntry"] = string.Empty; drRow["FirstTextBox"] = string.Empty; drRow["SecondTextBox"] = string.Empty; dt.Rows.Add(drRow); ViewState["applicationDetail"] = dt; GridView1.DataSource = ViewState["applicationDetail"]; } catch (Exception ex) { throw; } } 

InitializeGrid(); InitializeGrid();

GridView1.DataBind(); GridView1.DataBind();

On GridView1_RowDataBound Bind All your drop down controls 在GridView1_RowDataBound上绑定所有下拉控件

upto this will create a grid with one empty row. 到此为止,将创建一个带有一行空行的网格。

  1. Now On Add Button Click do following 现在在添加按钮上,单击执行以下操作

     protected void btnNewRow_Click(object sender, EventArgs e) { try { AddNewRowToGrid(); } catch (Exception ex) { throw ex; } } private void AddNewRowToGrid() { try { int rowIndex = 0; if (ViewState["applicationDetail"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"]; DataRow drCurrentRow = null; if (dtCurrentTable.Rows.Count > 0) { for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) { //extract the TextBox values _lblGuestId DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList; DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList; TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox; TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox; drCurrentRow = dtCurrentTable.NewRow(); drCurrentRow["RowNumber"] = i + 1; dtCurrentTable.Rows[i - 1]["FirstEntry"] = ddl1.SelectedValue; dtCurrentTable.Rows[i - 1]["SecondEntry"] = ddl2.SelectedValue; dtCurrentTable.Rows[i - 1]["FirstTextBox"] = txt1.Text; dtCurrentTable.Rows[i - 1]["SecondTextBox"] = txt2.Text; rowIndex++; } dtCurrentTable.Rows.Add(drCurrentRow); ViewState["applicationDetail"] = dtCurrentTable; GridView1.DataSource = dtCurrentTable; GridView1.DataBind(); } } else { Response.Write("ViewState is null"); } //Set Previous Data on Postbacks SetPreviousData(); } catch (Exception ex) { throw ex; } } private void SetPreviousData() { try { int rowIndex = 0; if (ViewState["applicationDetail"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"]; if (dtCurrentTable.Rows.Count > 0) { for (int i = 0; i < dtCurrentTable.Rows.Count; i++) { DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList; DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList; TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox; TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox; ddl1.SelectedValue = dtCurrentTable.Rows[i]["FirstEntry"].ToString(); ddl2.SelectedValue = dtCurrentTable.Rows[i]["SecondEntry"].ToString(); txt1.Text = dtCurrentTable.Rows[i]["FirstTextBox"].ToString(); txt2.Text = dtCurrentTable.Rows[i]["SecondTextBox"].ToString(); rowIndex++; } } } } catch (Exception ex) { throw ex; } } 
  2. For Deleting 删除中

On GridView1_RowCommand when check box is checked get row indexes of all the checked check box rows and keep it in some session or application variable. 在GridView1_RowCommand上,选中此复选框时,将获取所有选中的复选框行的行索引,并将其保留在某个会话或应用程序变量中。

On delete button click use that variable for deleting the rows. 在删除按钮上,单击使用该变量删除行。

I hope your problem will be solved. 希望您的问题能得到解决。

As per your comment i am adding GridView1_RowDataBound for drop down bindings 根据您的评论,我正在添加GridView1_RowDataBound用于下拉绑定

    protected void GridView1_RowDataBound(object sender,  GridViewRowEventArgs e)
    {
        try
        {
            DropDownList ddl1 = (e.Row.FindControl("ddlFirstEntry") as DropDownList);
            Label lbl1 = (e.Row.FindControl("lblFirstEntry") as Label);

            DropDownList ddl2 = (e.Row.FindControl("ddlSecondEntry") as DropDownList);
            Label lbl2 = (e.Row.FindControl("lblSecondEntry") as Label);                


            ddl1.Items.Clear();
            ddl1.AppendDataBoundItems = true;
            ddl1.Items.Add(new ListItem("-Select-", "-1"));

            ddl1.DataSource = ViewState["ddl1datasourse"];
            ddl1.DataTextField = "Value";
            ddl1.DataValueField = "Id";
            ddl1.DataBind();
            if (ddl1.SelectedValue != string.Empty && lbl1.Text != null)
                ddl1.SelectedValue = lbl1.Text.Trim();
            else
                ddl1.SelectedValue = "-1";

            ddl2.Items.Clear();
            ddl2.AppendDataBoundItems = true;
            ddl2.Items.Add(new ListItem("-Select-", "-1"));

            ddl2.DataSource = ViewState["ddl2datasourse"];
            ddl2.DataTextField = "Value";
            ddl2.DataValueField = "Id";
            ddl2.DataBind();
            if (ddl2.SelectedValue != string.Empty && lbl2.Text != null)
                ddl2.SelectedValue = lbl2.Text.Trim();
            else
                ddl2.SelectedValue = "-1";

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM