简体   繁体   English

如何在不使用asp.net刷新页面的情况下使用添加按钮向现有表中动态添加行?

[英]How to dynamically add row to existing table with add button and without page being refreshed in asp.net?

I have an existing table which is dynamically generated, the row contains set of controls like textboxes and dropdowns again dynamically generated. 我有一个动态生成的现有表,该行包含一组控件,例如文本框和下拉列表,也是动态生成的。 There is a "Add new row" button on the main page. 主页上有一个“添加新行”按钮。 On clicking the button a new blank row gets added to the table with all the previous entries set. 单击按钮后,新的空白行将被添加到表中,并设置所有先前的条目。

The problem occurs when we click the button, it causes the main form to refresh, is there a way to prevent this? 当我们单击按钮时会发生问题,它会导致主窗体刷新,有没有办法防止这种情况发生?

You will have to use UpdatePanel/Ajax to make this work without a complete page refresh. 您将必须使用UpdatePanel / Ajax来完成这项工作,而无需刷新整个页面。 This answer is pretty good. 这个答案很好。

The .aspx files code here : .aspx文件的代码在这里:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="step_by_step.aspx.cs" Inherits="Test_ankit_27Oct_Research_step_by_step" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
    #form1
    {
        height: 199px;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <br />
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
        Text="Outside Update Button (+2)" />
    <br />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            &nbsp;<asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                Text="Inside Update  Button (+1)" />
            <br />
            &nbsp;
            <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Label"></asp:Label>
            &nbsp;<br /> &nbsp;
            <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text="Label"></asp:Label>
            <br /> &nbsp;<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            <br />
            &nbsp;
            <br />
            &nbsp;
            <br />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
        </Triggers>

    </asp:UpdatePanel>
</div>
</form>

The .cs file code here : .cs文件代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_ankit_27Oct_Research_step_by_step : System.Web.UI.Page
{
    static int start_number_rows = 1; //initial counter default row as 1
    static int counter = start_number_rows;
    protected void Page_Init(object sender, EventArgs e)
   {
       ViewState["RowsCount"] = start_number_rows;
       Label1.Text = "Total Rows : "+counter.ToString();

  }
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        generate_table();
    }
    else
    {
        //the below part of the code is required to distinguish between autopost back of textbox 
        //and the autopost back of button controls

        string CtrlID = string.Empty;
        if (Request.Form["__EVENTTARGET"] != null &&
                 Request.Form["__EVENTTARGET"] != string.Empty)
        {

             generate_table();
             // for all postbacks except external and internal clicks

        }
        else
        {


            //to check which button or image button click caused the postback
            foreach (string controlID in Request.Form)
            {
                Control objControl = Page.FindControl(controlID);
                if (objControl is Button)
                {
                    CtrlID = objControl.ID;
                    if (CtrlID == "Button1")
                    {

                        //now the call will go to Button1_Click function


                    }
                    if (CtrlID == "Button2")
                    {

                        //now the call will go to Button2_Click function


                    }
                }
            }
        }
       //then let the control flow to button click events
    }
}
protected void generate_table()
{

    Table table = new Table();
    TableRow row;
    TableCell cell;
    TextBox tb;
    table.ID = "Table1";

    int s_rows = Convert.ToInt32(ViewState["RowsCount"].ToString());

    for (int k = 1; k <= s_rows; k++)
    {
        row = new TableRow();
        cell = new TableCell();

        tb = new TextBox();
        tb.ID = "tb_" + k;
        tb.TextChanged += new EventHandler(tb_TextChanged);
        tb.AutoPostBack = true;
        cell.Controls.Add(tb);

        row.Cells.Add(cell);
        table.Rows.Add(row);
    }

   PlaceHolder1.Controls.Add(table);
}

protected void setdata()
{
    Table table = (Table)Page.FindControl("Table1");
    if (table != null)
    {

        foreach (TableRow tr in table.Rows)
        {
            foreach (TableCell tc in tr.Cells)
            {
                foreach (Control ct in tc.Controls)
                {
                    if (ct is TextBox)
                    {

                        ((TextBox)ct).Text = Request.Form[ct.ID];
                    }
                    if (ct is DropDownList)
                    {
                        ((DropDownList)ct).Text = Request.Form[ct.ID];
                    }
                }
            }
        }
    }
}


protected void Button1_Click(object sender, EventArgs e)
{

    counter++;
    Label1.Text = "Total Rows : "+counter.ToString();
    //Label1.Text = "Refreshed at " + DateTime.Now.ToString();

    int new_rows_count = Convert.ToInt32(ViewState["RowsCount"]) + 1; //add one rows at a time
    ViewState["RowsCount"] = new_rows_count;
    generate_table();
    setdata();        //set the values of any of the previously generated  controls
}
protected void Button2_Click(object sender, EventArgs e)
{


     counter=counter+2;
     Label1.Text = "Total Rows : " + counter.ToString();
    //Label1.Text = "Refreshed at " + DateTime.Now.ToString();

    int new_rows_count = Convert.ToInt32(ViewState["RowsCount"]) + 2; //add 2 rows at a time
    ViewState["RowsCount"] = new_rows_count;

    generate_table();
    setdata();        //set the values of any of the previously generated  controls
}

protected void tb_TextChanged(object sender, EventArgs e)
{

    TextBox tb = (TextBox)sender;
    Label2.Text = "Text of textbox "+ tb.ID+ " changed to " + tb.Text;

}
}

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

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