views:

51

answers:

3

Hey guys, I have an ASP.NET GridView bound to a DataView that contains a DataTable. I'm not using a DataAdapter.

I want to update a row in my DataTable, so I do this:

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
    DataView dv = (DataView)Session["My_DataTable"];
    DataTable dt = dv.Table;
    int rowIndex = GridView1.Rows[e.RowIndex];
    dt.Rows[rowIndex]["FirstName"] = thenewfirstname;
    dt.Rows[rowIndex]["MI"] = thenewmi;
    dt.Rows[rowIndex]["LastName"] =thenewlastname;
    Session["My_DataTable"] = dv;
    //Reset the edit index.
    GridView1.EditIndex = -1;

    //Bind data to the GridView control.
    GridView1.DataSource = Session["My_DataTable"];
    GridView1.DataBind();
 }

The underlying DataView/DataTable is changed correctly, but the GridView contains both the old row before the edit, and the new row after the edit (that is, it adds an additional row with the new edits!).

For example, if we have :

...
Sammy S Samerson 
...

and change it to Sammy E Samerson the gridview says :

...
Sammy S Samerson
Sammy E Samerson
...

How do I fix this, what did I do wrong?

A: 

I don't think you want to do this in the RowUpdating Event try the RowUpdated event instead

Conrad Frix
A: 

A lot of strange things were happening.

The gist of all of the Bad Things was the DataView - because things were being reordered, the index of the GridView, and the index of the DataTable in the DataView weren't matching up. The DataTable had to be looped through untill the correct just-edited record was found.

rlb.usa
Thought so.....
Jeroen
+1  A: 

Hi,

Did you check the row index of the editing row. int rowIndex = GridView1.Rows[e.RowIndex]; you can directly use the e.RowIndex.

My Suggestion is to get the row by using any key field of the table.

for example

DataRow[] customerRow = 
dataSet1.Tables["Customers"].Select("CustomerID = 'ALFKI'");

customerRow[0]["CompanyName"] = "Updated Company Name";
customerRow[0]["City"] = "Seattle";

You can get the row values by using the cell position. Or use datakeynames for example :

string courseid = GridView1.Rows[e.RowIndex].Cells[3].Text;
Geetha