Insert an Updated Row to an ASP .Net GridView - asp.net

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?

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

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?

Dynamically update dropdownlist

I have this dropdownlist populated and everything. The only problem is that whenever I add a new item in the database through my website, the dropdownlist doesn't update for some reason.
private CurrentUser _cu = new CurrentUser();//just to check if use is an admin or not.
protected void Page_Load(object sender, EventArgs e)
{
_cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!_cu.CanReport) { Response.Redirect("~/default.aspx"); }
CurrentUser cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!IsPostBack)
{
foreach (PrefixAdd loc in cu.Prefix)//Prefix is a Property
{
ListItem x = new ListItem(loc.Prefix);
PrefixID.Items.Add(x);
}
}
}
#Wayne I'm using a store procedure to just insert a Prefix like Pre,yes,sey, etc. Then the list is populated with prefixes.
StringBuilder sbSQL = new StringBuilder(255);
sbSQL.Append(string.Format("exec insPrefix #Prefix=N'{0}';", PrefixBox.Text.Trim()));
string msg = string.Empty;
msg = (_oDAW.ExecuteNonQuery(sbSQL.ToString())) ? string.Format(Common.GetAppSetting(Common.ConfigKeys.User_Submit_Success),
PrefixBox.Text.Trim()) : Common.GetAppSetting(Common.ConfigKeys.SubmitFail); //this is a somewhat custom method for CS and databinding.
# Yuriy Rozhovetskiy Yea I add new items to this page with the dropdownlist.
Whenever you add an item to your database, you have to rebind your drop down list.
yourDropDown.DataSource = //...
yourDropDown.DataBind();
That is, DropDownLists (and other controls) have no way of knowing that their data has changed behind the scenes, they can't automatically detect it. You have to tell the controls to rebind their data manually.
Good job on the Page_Load(...){ if !(IsPostback) part.
Since you add new prefix on this page with some postback item you need to add this new item to PrefixID dropdown's Items collection and update the CurrentUser instance in Session right after you have add new prefix to database.

Updating a DataTable?

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;

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