且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将新行数据添加到 gridview asp.net c#

更新时间:2023-12-06 15:31:34

ASPX:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:GridView ID="GridView1" runat="server"/>

背后的代码:

public class Customer
{
    public Customer() { }
    public Customer(Customer cust)
    {
        ID = cust.ID;
        Name = cust.Name;
        FatherName = cust.FatherName;
        Email = cust.Email;
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public string FatherName { get; set; }
    public string Email { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
    List<Customer> lstCustomer = new List<Customer>();
    if (Session["dt"] != null)
    {
      lstCustomer = (List<Customer>)Session["dt"];
    }
    Customer customer = new Customer();
    customer.ID = int.Parse(TextBox1.Text);
    customer.Name = TextBox2.Text;
    customer.FatherName = TextBox2.Text;
    customer.Email = TextBox2.Text;
    lstCustomer.Add(new Customer(customer));
    GridView1.DataSource = lstCustomer;
    GridView1.DataBind();
    Session["dt"] = lstCustomer;
}

已更新!

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<Customer> lstCustomer = new List<Customer>();
        Customer customer = new Customer();

        customer.ID = 1;
        customer.Name = "John Cena";
        customer.FatherName = "John";
        customer.Email = "cena@gmail.com";
        lstCustomer.Add(new Customer(customer));

        customer.ID = 2;
        customer.Name = "Mokesh";
        customer.FatherName = "Rajnikant";
        customer.Email = "mokesh@gmail.com";
        lstCustomer.Add(new Customer(customer));

        customer.ID = 3;
        customer.Name = "Bilal Ahmad";
        customer.FatherName = "Kashif";
        customer.Email = "bilal@gmail.com";
        lstCustomer.Add(new Customer(customer));

        customer.ID = 4;
        customer.Name = "Chin Shang";
        customer.FatherName = "Shang Woe";
        customer.Email = "chinshang@gmail.com";
        lstCustomer.Add(new Customer(customer));
        Session["dt"] = lstCustomer;

    }
}