Click here to Skip to main content
15,891,902 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to Add record into Data Table in multiple time One Button Click Event Without Declare DataTable as Static.

e.g. I want add 10 record into Data Table when User press 10 Time Button


I am using this code but not working every Click event Data Table Clear
C#
DataTable dt_dr = new DataTable("Test");

dt_dr.Columns.Add(LedgerId, typeof(int));
dt_dr.Columns.Add(LedgerName, typeof(string));


DataRow dt_row;
dt_row = dt_dr.NewRow();
dt_row[LedgerId] = TextBox1.Text;
dt_row[LedgerName] = TextBox2.Text;
dt_dr.Rows.Add(dt_row);
Posted
Updated 21-Nov-11 0:20am
v6
Comments
_Tushar Patil 21-Nov-11 4:46am    
web application Or Windows App..?
Member 8413260 21-Nov-11 6:04am    
web application
Sunasara Imdadhusen 21-Nov-11 5:03am    
Is this our homework?
Member 8413260 21-Nov-11 6:06am    
Its Office Work

On button click u make one manual datatable with your headers as columns.
then add rows with data dynamically.
 
Share this answer
 
Hello Anuja,
Declare an object of DataTable at class level

Use bellow code in button click event

C#
protected void Button1_Click(object sender, EventArgs e)
 {
     try
     {
         //Check if previous session is exist
         if (Session["MyTable"] == null)
         {
             dtMyTable = new DataTable("MyTable");
             dtMyTable.Columns.Add("Id", typeof(int));
             dtMyTable.Columns.Add("LName", typeof(string));

         }
         else
         {
             //If yes then get it from current session
             dtMyTable = (DataTable)Session["MyTable"];
         }

         //Add new row every time
         DataRow dt_row;
         dt_row = dtMyTable.NewRow();
         dt_row["Id"] = TextBox1.Text;
         dt_row["LName"] = TextBox2.Text;
         dtMyTable.Rows.Add(dt_row);

         //Update session table
         Session["MyTable"] = dtMyTable;
     }
     catch (Exception ex)
     {

         Response.Write(ex.Message);
     }
 }
 
Share this answer
 
Comments
Member 8413260 21-Nov-11 22:51pm    
Thanks Buddy,
Its working fine.............

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900