Updating a DataTable? - asp.net

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 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.

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;

Related

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

Insert an Updated Row to an ASP .Net GridView

I am updating a GridView dataRow on GridView_RowUpdating event and Updating the database too.
on GridView_RowUpdating event i wrote c# code to update the database and after successfull update of database i am creating a class object of this row. and trying to bind this row to another grid.
Database is getting updated but another grid is not being updated.
Any Solution??
Here is my code
Grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Update Operation for First Grid
...
...
Class1 ObjRow = new Class1();
ObjRow.Status = Updated.
List<Class1> lst = GetUpdatedDetails();
GridView1.DataSource = lst;
GridView1.DataBind();
lst = new List<Class1>();
lst.add(ObjRow)
// Here Its Failing
GridView2.DataSource = lst;
GridView2.DataBind();
}
Is the second Gridview in an UpdatePanel? Try adding the new row then refreshing the Page. Doe s this have any effect?

How to bind data column to textbox?

I have datagridview and textboxes on form. I load records from different tables when user clicks any one radiobutton. Data in grid is shown perfectly. I want to show values of the row in those textboxes.
One solution can be: binding data from dataset.
Second one can be: transfer values of each cell of row to respective textbox.
Please help me. And, please tell me which one is better or is there any other method which is even better than these two.
Thanks in advance.
Try using a BindingSource
BindingSource bindingSource = new BindingSource();
DataSet dataSet = new DataSet();
DataAdapter da1 = new DataAdapter("Select * from Customers", conn1);
DataAdapter da2 = new DataAdapter("Select * form Orders", conn1);
da1.Fill(dataSet,"Customers");
da2.Fill(dataSet,"Orders");
//Let we set Customers table as bindiningSource datasource
bindingSource.DataSource = dataSet.Tables["Customers"];
private void RadioButtonCustomers_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonCustomers.Checked==true)
bindingSource.DataSource =dataSet.Tables["Customers"];
}
private void RadioButtonOrders_CheckedChanged(object sender, EventArgs e)
{
if(radioButtonOrders.Checked==true)
bindingSource.DataSource = dataSet.Tables["Orders"];
}
//First param of Binding is to which prop of TextBox to bind the value
//Second param is the data source
//Third param is the data member or the column name of the table as datasource, so
//we have to get that table from casting the bindingSource datasource prop and casting it
//to DataTable obj and after that to take the ColumnName prop of the desired column
textBox1.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[0].ColumnName));
textBox2.DataBindings.Add(new Binding("Text",bindingSource,((DataTable)bindingSource.DataSource).Columns[1].ColumnName));
etc...
Even if you change the datasource prop of bindingSource, textboxes will remain binded to rowvalue of first and second column
Hope this help.
Sir I done it making a simple WindowsForm with 2 radio buttons, 2 textboxes and datagridview
here is the sln file http://www13.zippyshare.com/v/98590888/file.html this must help u.
I tried many options to display value in textbox on the same form, but it was not working as datagridview could display records of two different tables.
Instead, I used the following event of datagridview:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
this.dataGridView1.SelectionChanged += new System.EventHandler(this.DisplayValueinTextBox);
}
In DisplayValueinTextBox, I wrote following code based on numbers of columns displayed for each table:
private void DisplayValueinTextBox(object sender, EventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedCells[0].Value.ToString();
textBox2.Text = dataGridView1.SelectedCells[1].Value.ToString();
textBox3.Text = dataGridView1.SelectedCells[2].Value.ToString();
if (tblGrid == "Employee") //name of table which has more columns in grid
{
textBox4.Text = dataGridView1.SelectedCells[3].Value.ToString();
textBox5.Text = dataGridView1.SelectedCells[4].Value.ToString();
textBox6.Text = dataGridView1.SelectedCells[5].Value.ToString();
}
this.dataGridView1.SelectionChanged -= new System.EventHandler(this.DisplayValueinTextBox); //removed it as I was getting error.
}
catch (Exception exdisp)
{
MessageBox.Show(exdisp.Message);
}
}
I also changed SelectionMode property of dataGridView to FullRowSelect. This will ensure that textbox1 is displaying value of SelectedCells[0] even if user clicks any cell.
I still hope there is even a better option, so I wait for comments on this.

GridView as DataTable source sorts only for the first time

I implemented sorting on my GridView with a DataTable as DataSource by using code from this MSDN link. However, my grid sorts for the first time when I click any column, and after that it does not sort on clicking any other column.
Code in the PageLoad() event -
if (!Page.IsPostBack)
{
HView hv = new HView ();
DataTable HTable = new DataTable("hTable");
HTable = hv.FillTable();
Session["hTable"] = HTable;
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
Code in the Sorting event -
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
}
Does anybody have an idea of what I may be doing wrong?
EDIT: I just realized this. If I select a particular row, I have another view that gets populated with details about that row. When I view some rows details first before trying to sort any columns, then sorting works perfectly fine, any number of times. However, if I try to sort before selecting a row, it works only once.
You are using the DataTable as DataSource in the sorting event, but you should use the sorted view instead. Sorting the view won't change the sort order of the data in the table, just the order in the view.
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = notesDT.DefaultView;
GridView2.DataBind();
}
}
Edit: Although that i've just noticed that you're using rhe same code from MSDN.
You could also try to create a new DataTable from the view:
GridView2.DataSource = notesDT.DefaultView.ToTable(true);
You don't need stored the data table into a session. Actually putting the entire data table into session is not a good idea at all. Any particular reason for that?

How do I sort my datagrid?

Editing some legacy code that populates a datagrid entirely in code. I need to order it by two columns but I don't know how. Which event do I hook into and what can I do to order the 2nd and 3rd columns (that contain dates) in order of most recent first?
Edit: Argh it's a datagrid
Datagrid or GridView?
you can create a dataview and sort it (in the constuctor) then bind this back to the grid in the "sorting" event
something like this might be what you're after
protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Your data
DataTable dt = new DataTable();
// Create the view
DataView dv = new DataView(dt, "", "COLUMN_TO_SORT", DataViewRowState.CurrentRows);
// Rebind
myGridView.DataSource = dt;
myGridView.DataBind();
}

Resources