简体   繁体   中英

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. 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. Here is an image of how I want the GridView to be:

Each row has 2 dropdown lists, two textbox and a button 在此处输入图片说明

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. 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

 <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

     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();

GridView1.DataBind();

On GridView1_RowDataBound Bind All your drop down controls

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.

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

    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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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