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

时间:2015-11-17 19:07:11

标签: c# asp.net gridview

嗨,我有一个很大的问题,因为我不知道从哪里开始。我需要创建一个Gridview,它必须在它下面的按钮," Create Row"按钮和"删除行"按钮。我希望每次"创建行"按钮被按下要添加到GridView的新行,但主要问题是我需要用不同的控件填充新行,例如DropDownLists和TextBox,但我不知道如何正确地执行它。这是我想要GridView的图像:

  

每行有2个下拉列表,两个文本框和一个按钮   enter image description here

我知道我需要将GridView绑定到数据源(如dataTable),但我不知道是否可以使用TextBox或DropDownLists等控件。很抱歉,如果我没有添加任何代码,因为我真的不知道从哪里开始。谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解得对,你可以遵循:

  1. 创建Gridview
  2. <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. 然后在Page_Load中的Code后面调用此方法

      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;
          }
      }
      
    2. InitializeGrid();

      GridView1.DataBind();

      在GridView1_RowDataBound上绑定所有下拉控件

      这将创建一个空行的网格。

      1. 现在开启添加按钮单击“执行以下操作”

        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. 用于删除

      3. 在GridView1_RowCommand上选中复选框时,获取所有已选中复选框行的行索引,并将其保留在某个会话或应用程序变量中。

        在删除按钮上,单击使用该变量删除行。

        我希望你的问题能够得到解决。

        根据你的评论我正在为下拉绑定添加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;
                }
            }