Click here to Skip to main content
15,118,323 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi
I have been trying to add a new row and add textbox value in my gridview but only if the gridview is not empty. Now I managed to add textbox value if the gridview is empty am strugling with adding a new row. Check the code below on how to add textbox value to a gridview

C#
DataTable dT = new DataTable();
            dT.Columns.Add("Reason", typeof(string));
            Session["dt"] = dT;

       DataTable dTable=(DataTable)Session["dt"];
       DataRow dr = dT.NewRow();

            if(grvPayments.Rows.Count==0)
            {
       dr["Reason"] = txtReason.Text;

      
           dTable.Rows.Add(dr);


           grvPayments.DataSource = dT;
           grvPayments.DataBind();
            }
      else
           {  
             //Create new row and add textbox value

            }
Posted
Updated 21-Feb-12 23:07pm
Comments
Mahmud Hasan 22-Feb-12 3:18am
   
In which event you are trying to do this?
Anele Ngqandu 22-Feb-12 7:06am
   
Onclick Event. But the button is not inside the gridview
Varun Sareen 22-Feb-12 8:10am
   
have you tried to do something according to my solution. As i have done that previously also and it worked smoothly

In that case dear friend, you need to retrieve the already added row in the grid view into the datatable which should be the clone of the earlier datatable means you have to make a new datatable with the same columns as in the gridview and then by applying a foreach loop on the grid (with one row already added), add the same row data into the new cloned datatable.

Now the moment all the rows already added to the grid is being added to the clone datatable then you have to add one blank row with one column for textbox being updated into one of the respective blank row.

And after completing all this bind the newly created datatable to the gridview by clearing all rows first.

This will definitely solve your purpose.
   
Please try it out this code

C#
DataTable dT = new DataTable();
if(Session["dt"]=null)
{
   dT.Columns.Add("Reason", typeof(string));
   DataRow dr = dT.NewRow();
   dr["Reason"] = txtReason.Text;
   dT.Rows.Add(dr);
   Session["dt"] = dT;
   grvPayments.DataSource = dT;
   grvPayments.DataBind();
}        
else
{  
   dT=(DataTable)Session["dt"];
   DataRow dr = dT.NewRow();
   dr["Reason"] = txtReason.Text;
   dT.Rows.Add(dr);
   Session["dt"] = dT;
   grvPayments.DataSource = dT;
   grvPayments.DataBind();
}
   
v3

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