[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 389
  • Last Modified:

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?
0
Tina_Bhole
Asked:
Tina_Bhole
  • 4
  • 2
  • 2
1 Solution
 
John ClaesCommented:
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();
        }



0
 
Tina_BholeAuthor Commented:
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.
0
 
CodeCruiserCommented:
You have to store the datatable in the session and use that instead of CCRHeaderDetails.DataSource. Call the DataBind() after adding the row.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Tina_BholeAuthor Commented:
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.
0
 
John ClaesCommented:
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
0
 
Tina_BholeAuthor Commented:
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.
0
 
CodeCruiserCommented:
Looks like you did not get the point. As ASP.NET is stateless, CCRHeaderDetails.DataSource will be null when the page is posted back. So

DT1 = (DataTable)CCRHeaderDetails.DataSource;

makes DT1 null as well hence the reference exception that you are getting.

Add the end of your page load, after this line

CCRHeaderDetails.DataBind();

add
Session["DT"] = DT1;

Then instead of
DT1 = (DataTable)CCRHeaderDetails.DataSource

use

DT1 = (DataTable)Session["DT"];
0
 
Tina_BholeAuthor Commented:
Thanks a lot, this has solved my problem.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now