Link to home
Start Free TrialLog in
Avatar of Tina_Bhole
Tina_Bhole

asked on

Adding and removing rows from a grid view in asp.net

___________________________Asp.net Code_________________________

<asp:Button  runat="server" ID="AddColumn" Text="Add Details" OnClick="AddColumnDetails"/>
<asp:Button  runat="server" ID="removeHeaderentry" Text="Remove Entry" OnClick="RemoveHeaderEntry"/>

_________________________C# Code _____________________________

public partial class Generate_CCR_Rule : System.Web.UI.Page
    {
        DataTable DT1 = new DataTable();
        DataRow DR1;
       
protected void Page_Load(object sender, EventArgs e)
        {
           //DT1 is the Data source for the Gridview CCRHeaderDetails

            DT1.Columns.Add(new DataColumn("Column Name", typeof(string)));
            DT1.Columns.Add(new DataColumn("CCR Header Rule Entry", typeof(string)));
            CCRHeaderDetails.DataSource = DT1;
            CCRHeaderDetails.DataBind();
        }

 protected void AddColumnDetails(object sender, EventArgs e)
        {
      DR1 = DT1.NewRow();
                DR1["Column Name"] = "Some Text"
                DR1["CCR Header Rule Entry"] = "Some Text";      
                DT1.Rows.Add(DR1);
               CCRHeaderDetails.DataBind();

      DR1=null;
        }

 protected void RemoveHeaderEntry(object sender, EventArgs e)
        {                                          // hdnHSelect is the hidden variable which has the index of selected row from CCRHeaderDetails
           GridViewRow row = CCRHeaderDetails.Rows[int.Parse(hdnHSelect.Value)];
            DataRow dr = (row.DataItem as DataRowView).Row;
            DT1.Rows.Remove(dr);
            CCRHeaderDetails.DataSource = DT1;
            CCRHeaderDetails.DataBind();
        }

I have 2 problems here,
Firstly, when I click on "Add Details" button, it overwrites the row in the grid view (CCRHeaderDetails) every single time instead of creating a new row and adding it to the grid view
Secondly, the code for "Remove Entry" button is not working.

Could someone please help?
Avatar of John Claes
John Claes
Flag of Belgium image

The issue is the folowing : You're always starting with a EMPTY DT1 because the Pages are STATELESS ;-)
So you must fill the DT before you can do something

so what must be changed to get this done :



protected void AddColumnDetails(object sender, EventArgs e)
        {
                DT1 = CCRHeaderDetails.DataSource;
                DR1 = DT1.NewRow();
                DR1["Column Name"] = "Some Text"
                DR1["CCR Header Rule Entry"] = "Some Text";      
                DT1.Rows.Add(DR1);
                CCRHeaderDetails.DataBind();
                DR1=null;
        }

 protected void RemoveHeaderEntry(object sender, EventArgs e)
        {        
            DT1 = CCRHeaderDetails.DataSource;                  
            GridViewRow row = CCRHeaderDetails.SelectedRow;
            DataRow dr = (row.DataItem as DataRowView).Row;
            DT1.Rows.Remove(dr);
            CCRHeaderDetails.DataSource = DT1;
            CCRHeaderDetails.DataBind();
        }



Avatar of Tina_Bhole
Tina_Bhole

ASKER

Hi,

Sorry, but the recommended change did not have any effect on the output. I am still not able to add new rows to the gridview. It is still overwriting every time.

I had to use
DT1 = (DataTable)CCRHeaderDetails.DataSource;
instead of
DT1 = CCRHeaderDetails.DataSource;

In the RemoveHeaderEntry procedure,
GridViewRow row = CCRHeaderDetails.Rows[int.Parse(hdnHSelect.Value)];
gives following error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

If I use GridViewRow row = CCRHeaderDetails.SelectedRow; instead of the above statement, the variable "row" stores null value and DT1.Rows.Remove(dr); statement gives error.
Avatar of Nasir Razzaq
You have to store the datatable in the session and use that instead of CCRHeaderDetails.DataSource. Call the DataBind() after adding the row.
Hello,
Please bare with me as I am still learning ASP.net.
I did not understand this. I have declared the data table inside the class. So, if I am not wrong, it's scope should be local to the methods/ procedures used inside that class.  So, how does DT1 become empty? and If I declare it within the AddcolumnDetails, it will declare it every time I add click on add button.

I am calling DataBind() everytime I add to/ remove from the GridView/ DT1.

Could you please explain?

Thanks.
Tina ,


Because you're in a webPage (==> read stateless) every time you start an Event
the Page is created again on ServerSide.

so initialisation is called ==>
       DataTable DT1 = new DataTable();

and after the event is executed the Page_Load is called to ensure you'll get a response that is a page to show in the browser.

So if the Page_OnLoad filles DT1 from the DataBase CodeCruiser has a point
If you don't want everything inside the DataBase until Confirmed by the user ==>
Please place everything inside the folowing If
If Not IsPostBack Then
end if

Why ?
Every Event Called is done by creating a PostBack
The PAge_Onload will then not Call the database and refill the DataGRid.

poor beggar
Ok. I have put everthing in one procedure now.

protected void AddColumnDetails(object sender, EventArgs e)
        {
            string S="some text";

                DataTable DT1 = new DataTable();
                DataRow DR1;
                DT1.Columns.Add(new DataColumn("Column Name", typeof(string)));
                DT1.Columns.Add(new DataColumn("CCR Header Rule Entry", typeof(string)));
             
                DT1 = (DataTable)CCRHeaderDetails.DataSource;
                DR1 = DT1.NewRow();
                DR1["Column Name"] = CCRList.Rows[int.Parse(hdnListitem.Value)].Cells[0].Text;
                DR1["CCR Header Rule Entry"] = S;      
                DT1.Rows.Add(DR1);

                CCRHeaderDetails.DataSource = DT1;
                CCRHeaderDetails.DataBind();

                DT1 = null;
                DR1 = null;
            }

This gives me error at DR1=DT1.NewRow(); : "Object reference not set to an instance of an object".

Just wanted to check, how do I copy data from grid view to the data table. Should I be using a for loop to go through each grid view row.
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot, this has solved my problem.