从ASP.NET GridView添加并删除行

发布于 2025-02-08 07:03:58 字数 6699 浏览 1 评论 0原文

我正在尝试使用动态控件在按钮上创建行,请单击asp.net gridview。添加零件是完成的,但由于删除了创建的行的删除。这样做是为了添加更多行:

asp.net

 <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDeleting">
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
            </Columns>
</asp:GridView>

c#

int count = 1;

private void SetInitialRow()
{
    DataTable dt = new DataTable();
    DataRow dr = null;
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
    dt.Columns.Add(new DataColumn("Column2", typeof(string)));
    dt.Columns.Add(new DataColumn("Column3", typeof(string)));
    dr = dt.NewRow();
    dr["RowNumber"] = 1;
    dr["Column1"] = string.Empty;
    dr["Column2"] = string.Empty;
    dr["Column3"] = string.Empty;
    dt.Rows.Add(dr);

    ViewState["CurrentTable"] = dt;

    Gridview1.DataSource = dt;
    Gridview1.DataBind();
}

private void AddNewRowToGrid()
{
    int rowIndex = 0;

    if (Session["count"] != null)
        count = (int)Session["count"];
    count++;
    Session["count"] = count;

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                Label label1 = (Label)Gridview1.Rows[rowIndex].Cells[0].FindControl("Label1");
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                drCurrentRow = dtCurrentTable.NewRow();
        
                drCurrentRow["RowNumber"] = count ;

                dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                rowIndex++;
            }
            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }

    SetPreviousData();
}

private void SetPreviousData()
{
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                box1.Text = dt.Rows[i]["Column1"].ToString();
                box2.Text = dt.Rows[i]["Column2"].ToString();
                box3.Text = dt.Rows[i]["Column3"].ToString();

                rowIndex++;
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetInitialRow();
    }
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

对于删除行,尝试了以下代码,但似乎有某种行索引不匹配,没有删除关联的行打开按钮单击:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

        if (dtCurrentTable.Rows.Count > 0)
        {
            int rowIndex = Convert.ToInt32(e.RowIndex);
       
            dtCurrentTable.Rows[rowIndex].Delete();
       
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                rowIndex--;
            }

            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }

        SetPreviousData();
    }
}

删除零件有什么我做错了什么?

I am trying to create rows with dynamic controls on button click in ASP.NET GridView. The adding part is done, but stuck with the deletion of rows created. Done this for adding more rows:

ASP.NET:

 <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDeleting">
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
            </Columns>
</asp:GridView>

C#:

int count = 1;

private void SetInitialRow()
{
    DataTable dt = new DataTable();
    DataRow dr = null;
    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
    dt.Columns.Add(new DataColumn("Column2", typeof(string)));
    dt.Columns.Add(new DataColumn("Column3", typeof(string)));
    dr = dt.NewRow();
    dr["RowNumber"] = 1;
    dr["Column1"] = string.Empty;
    dr["Column2"] = string.Empty;
    dr["Column3"] = string.Empty;
    dt.Rows.Add(dr);

    ViewState["CurrentTable"] = dt;

    Gridview1.DataSource = dt;
    Gridview1.DataBind();
}

private void AddNewRowToGrid()
{
    int rowIndex = 0;

    if (Session["count"] != null)
        count = (int)Session["count"];
    count++;
    Session["count"] = count;

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                Label label1 = (Label)Gridview1.Rows[rowIndex].Cells[0].FindControl("Label1");
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                drCurrentRow = dtCurrentTable.NewRow();
        
                drCurrentRow["RowNumber"] = count ;

                dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                rowIndex++;
            }
            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }

    SetPreviousData();
}

private void SetPreviousData()
{
    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                box1.Text = dt.Rows[i]["Column1"].ToString();
                box2.Text = dt.Rows[i]["Column2"].ToString();
                box3.Text = dt.Rows[i]["Column3"].ToString();

                rowIndex++;
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetInitialRow();
    }
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

For deleting rows, tried the below code but seems like it's having some kind of row index mismatch and doesn't delete associated row on button click:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

        if (dtCurrentTable.Rows.Count > 0)
        {
            int rowIndex = Convert.ToInt32(e.RowIndex);
       
            dtCurrentTable.Rows[rowIndex].Delete();
       
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;

                rowIndex--;
            }

            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }

        SetPreviousData();
    }
}

Is there anything that I am doing wrong with the delete part?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凶凌 2025-02-15 07:03:58

根本不清楚为什么您将所有这些额外的代码添加到添加行中????

如果要默认值,为什么不从持久的数据表中获取它们,为什么要打扰网格呢? - 我认为您不需要所有这些代码。

现在,使它真的有效吗?您确实需要一个额外的例行程序 - 网格到桌子。

但是,让我们现在离开。

第二,请注意,由于数据表是一个对象,一旦将对象指向ViewState,更改也重新指向查看状态(您不必重新散发回ViewState。使用字符串或INT计数器 - 是的您这样做,但不使用对象(您只能使用指向给定的对象的指针

)一个按钮进入GV,并为此进行单击事件

。 包含/行的原因。

显示/显示/ 将许多自定义控件添加到网格视图中,每个自定义控件都需要模板标签,并且有很多控件。进入ListView并不需要这些模板标签。但是,让我们留下这个技巧的下一步。

另外,如果数据库来自数据库,许多人没有意识到,您可以将整个Datatalbe发送回数据库,并且可以使用一个命令执行此保存,该命令将自动删除所有更新,插入甚至删除。当然,在您的示例中,我们只是播放和构建100%的内存数据表,但是如果/何时数据词来自数据库,则整个设置在相同的情况下工作。

因此,我将丢弃内置的删除按钮。

我会丢弃行数据约束代码。

我还考虑将添加按钮移出GV。您可以打开“ showheaderwhenempty” = true。然后将显示标头 - 即使没有数据也是如此。但是没有数据,页脚不会显示,因此,如果删除一行,则无法添加该行。

因此,我们的标记是:

注意关闭,我不想编写代码来加载每一行 - 我们不必这样做,所以请注意如何添加text = expression。同样,更少的代码。

<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" 
    AutoGenerateColumns="false" CssClass="table"
    ShowHeaderWhenEmpty="true" Datakeys="RowNumber" >
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
                            OnClick="ButtonAdd_Click" cssclass="btn"/>
                    </FooterTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText ="Delete">
                    <ItemTemplate>
                        <asp:Button ID="cmdDelete" runat="server" Text="Delete" CssClass="btn"
                            OnClick="cmdDelete_Click"
                            OnClientClick = '<%# "return confirm(\"Really delete this row " + 
                                Container.DisplayIndex + " (" +
                                Eval("RowNumber")  + ")" + "\");" %>'
                            />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
</asp:GridView>

以及您如何启动页面?超越重要!!!

因此,我们有此代码:

   DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            SetInitialRow();
        else
            dt = ViewState["CurrentTable"] as DataTable;                
    }


    private void SetInitialRow()
    {
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
        dt.Columns[0].AutoIncrement = true;
        //Set the Starting or Seed value.
        dt.Columns[0].AutoIncrementSeed = 1;
        //Set the Increment value.
        dt.Columns[0].AutoIncrementStep = 1;


        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;

        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

请注意我如何将表移至班级级别。

现在要添加的代码是这样:

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        GridToTable();

        DataRow MyNewRow = dt.NewRow();
        dt.Rows.Add(MyNewRow);
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

删除代码是:

    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        GridToTable();

        Button cmdDel = sender as Button;
        GridViewRow gRow = cmdDel.NamingContainer as GridViewRow;

        // get row to delete

        int RowDel = gRow.RowIndex;

        dt.Rows[RowDel].Delete();
        Gridview1.DataSource = dt;
        Gridview1.DataBind(); 
    }

因此,如上所述,上面很大,可以使这项工作。如前所述,如果我们要允许数据编辑(假设是),那么我们还需要一个将网格移回数据的例程。

因此,当您点击“保存”按钮时,我们致电GridTotable。

因此,当您点击“添加”按钮时,我们将网格拨打到表格。

因此,当您点击删除按钮时,我们将网格拨打到表格。

换句话说,我们确实需要在添加之前将所有编辑保存回表中,或者删除甚至要将表保存到数据库中。

因此,我们需要这个例程:

    void GridToTable()
    {
        // send current grid back to table.
        foreach (GridViewRow gRow in Gridview1.Rows)
        {
            DataRow OneRow = dt.Rows[gRow.RowIndex];

            OneRow["Column1"] = (gRow.FindControl("TextBox1") as TextBox).Text;
            OneRow["Column2"] = (gRow.FindControl("TextBox2") as TextBox).Text;
            OneRow["Column3"] = (gRow.FindControl("TextBox3") as TextBox).Text;
        }
    }

Not at all clear why you have all that extra code in add row????

If you want to default values, why not take them from the persisted datatable, and why bother with the grid??? - I don't think you need all that code.

Now, to make this really work? You do want a extra routine - Grid to table.

but, lets leave that for now.

2nd, note that because data table is a object, once you point the object to viewstate, then changes ALSO point back to view state (you don't have to re-save back into viewstate. With a string, or int counter - yes you do, but not with objects (since then you only really working with a pointer to the given object).

Also, don't bother with the built in GV delete button - it really is more pain then it is worth. Just drop in a button into the GV, and wrire up a click event. That way you don't have to mess with the row data bound event to shove in the client side confirm you have.

Also, for most grids, you don't need to show/display/include/have the row ID. In fact for reasons of secuirty, in most cases I don't display the database PK row id (and you don't have to).

And one more FYI: When you start to add a LOT of custom controls to a grid view? Well, it always painful that each custom control needs that template tags. And with quite a few controls, that becomes really messy fast. So, I suggest a ListView, as each custom control dropped into the ListView does not requite those template tags. But, lets leave this tip for next around around.

Also, MANY do not realize that you can send a whole datatalbe BACK to the database if the datatable came from a database, and can execute this save back WITH ONE command that will automatic write back all updates, inserts and even deletes. Of course in your example, we just playing and building a 100% in-memory data table, but this whole setup works near the same if/when the datatable was from a database.

So, I would dump the built in delete button.

I would dump the row data bound code.

I also would consider moving the add button OUT of the GV. You can turn on "ShowHeaderWhenEmpty" = true. that will THEN display the header - even without data. But without data, the footer DOES NOT show, and thus if you delete the one row, you be unable to add that row.

So, our markup is this:

NOTE close, I did not want to write code to load up each row - we don't have to, so note how I added the Text = expression. Again, less code.

<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" 
    AutoGenerateColumns="false" CssClass="table"
    ShowHeaderWhenEmpty="true" Datakeys="RowNumber" >
            <Columns>
                <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                <asp:TemplateField HeaderText="Header 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Header 3">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
                            OnClick="ButtonAdd_Click" cssclass="btn"/>
                    </FooterTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText ="Delete">
                    <ItemTemplate>
                        <asp:Button ID="cmdDelete" runat="server" Text="Delete" CssClass="btn"
                            OnClick="cmdDelete_Click"
                            OnClientClick = '<%# "return confirm(\"Really delete this row " + 
                                Container.DisplayIndex + " (" +
                                Eval("RowNumber")  + ")" + "\");" %>'
                            />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
</asp:GridView>

And HOW you start the page up? Beyond important!!!

So, we have this code:

   DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            SetInitialRow();
        else
            dt = ViewState["CurrentTable"] as DataTable;                
    }


    private void SetInitialRow()
    {
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
        dt.Columns[0].AutoIncrement = true;
        //Set the Starting or Seed value.
        dt.Columns[0].AutoIncrementSeed = 1;
        //Set the Increment value.
        dt.Columns[0].AutoIncrementStep = 1;


        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;

        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

Note how I moved the table to class level.

Now code to add is this:

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        GridToTable();

        DataRow MyNewRow = dt.NewRow();
        dt.Rows.Add(MyNewRow);
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

And code to delete is this:

    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        GridToTable();

        Button cmdDel = sender as Button;
        GridViewRow gRow = cmdDel.NamingContainer as GridViewRow;

        // get row to delete

        int RowDel = gRow.RowIndex;

        dt.Rows[RowDel].Delete();
        Gridview1.DataSource = dt;
        Gridview1.DataBind(); 
    }

So, as noted, above quite much makes this work. As noted, if we are to allow editing of the data (assume yes), then we need one more routine that moves grid back to data.

So, when you hit a save button, we call GridToTable.

So, when you hit a add button, we call Grid to Table.

So, when you hit delete button, we call Grid to table.

In other words, we REALLY need to save all edits BACK to the table before we add, or delete or even want to save the table to a database.

So, we need this routine:

    void GridToTable()
    {
        // send current grid back to table.
        foreach (GridViewRow gRow in Gridview1.Rows)
        {
            DataRow OneRow = dt.Rows[gRow.RowIndex];

            OneRow["Column1"] = (gRow.FindControl("TextBox1") as TextBox).Text;
            OneRow["Column2"] = (gRow.FindControl("TextBox2") as TextBox).Text;
            OneRow["Column3"] = (gRow.FindControl("TextBox3") as TextBox).Text;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文