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

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

Related

Filtered data refreshes to unfiltered data when clicking next page of web forms GridView

I have a web forms project that has one filter. When the user filters the data and clicks on the next page, the filter seems to get taken off and the default data is displayed. How can I fix this? Is it the OnPageIndexChanging attribute method that needs updating? I've shown the code behind below for the ONPageIndexChanging method and the method used to bind the data (had to cut some out to get rid of the "too much code" error but if I'm missing anything that would be helpful, please let me know.)
protected void dashboard_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dashboard.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
void BindDataToGridView(SqlCommand cmdSQL = null)
{
// default sql
if (cmdSQL is null)
{
cmdSQL = new
SqlCommand("SELECT TabID, TabName, Title, CreatedOnDate, TabPath From [tableName].[dbo].[Tabs] Order By TabName");
}
var connectionFromConfig = WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
using (cmdSQL)
{
cmdSQL.Connection = new SqlConnection(connectionFromConfig);
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
dashboard.DataSource = rst;
dashboard.DataBind();
}
}
}
In place of your BindDataToGridView() for the paging event?
Call the SAME routine you have for the button click to filter the dates.
(you could even pull out the code for the button click into a separate routine. That routine filters by date, so have both your button click to filter, and the page index change event call that same routine.
So, for paging, you have to call the routine with the filter. This kind of suggests that you want one routine to load the grid, and it has to figure out if you have a filter or not. So, you might check for start/end date being blank. this would allow both page load event, the filter button, and the data page change event ALL to call ONE common routine.
So, a few things:
If you going to bind a grid/list view? and page? And filter?
(3 issues)?
Then make ONE common routine for all to call.
Say like this:
void BindDataToGridView()
{
SqlCommand cmdSQL = new SqlCommand("");
cmdSQL.CommandText = "SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName Order By TabName";
if (startDate.Text != "")
{
// filter
cmdSQL.CommandText =
"SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName " +
"WERE CreatedOnDate >= #Start AND <= #End ORDER By TabName";
cmdSQL.Parameters.Add("#Start", SqlDbType.Date).Value = startDate.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Date).Value = endDate.Text;
}
using (cmdSQL)
{
cmdSQL.Connection = new SqlConnection(conString);
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
dashboard.DataSource = rst;
dashboard.DataBind();
}
}
So now we are NOT passing the filter. You could I suppose also put the sql or the status of the filter into view state, and have the filter routine check this, but you better off to do the above.
In fact, I often suggest that we filter the reocrdset against its built in "view", as that can save database hits, but it don't matter.
So, when introducing filters? AND paging? You have to keep the above in mind.
So, now we have one routine for page load, the button click and the pager changing index code.

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.

Positioning of DDL items?

i have a dropDownList which gets its data from a database. Now after the data has bound, i programmatically add another listItem to the ddl, like so:
protected void ddlEffects_DataBound(object sender, EventArgs e)
{
DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList;
ddl.Items.Add(new ListItem("","0")); //Adds an empty item so the user can select it and the item doesnt provide an effect
}
It all works, but the problem is that the newly added listItem appears at the bottom of the DDL. I want it to be the first item. I tried making the value 0, but its still at the bottom. Is there any way to put it at the top?
Thanks!
Check into the ddl.Items.Insert method that will allow you to insert items at a specific location.
Like this for example:
using (Entities db = new Entities())
{
ddlDocumentTypes.DataSource = (from q in db.zDocumentTypes where (q.Active == true) select q);
ddlDocumentTypes.DataValueField = "Code";
ddlDocumentTypes.DataTextField = "Description";
ddlDocumentTypes.DataBind();
ddlDocumentTypes.Items.Insert(0, "--Select--");
ddlDocumentTypes.Items[0].Value = "0";
}
Which using EF loads the DDL with items for the database, and then inserts at position zero a new item.

ASP.net DataTable doesn't store new rows

In my simple starter asp page I create a DataTable and populate it with two rows. The web site allows users to add new rows. My problem is the DataTable doesn't save the information. I've stepped through the code and the row gets added but the next time a row is added it's not there, only the original two and the newest one to get entered.
I have gotten around this, in an inelegant way, but am really curious why the new rows are being saved.
My code:
protected void Page_Load(object sender, EventArgs e)
{
_Default.NameList = new DataTable();
DataColumn col = new DataColumn("FirstName", typeof(string));
_Default.NameList.Columns.Add(col);
col = new DataColumn("LastName", typeof(string));
_Default.NameList.Columns.Add(col);
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
_Default.NameList.Rows.Add(row);
row = _Default.NameList.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Doe";
_Default.NameList.Rows.Add(row);
}
protected void AddButton_Click(object sender, EventArgs e)
{
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = this.TextBox1.Text;
row["LastName"] = this.TextBox2.Text;
_Default.NameList.Rows.Add(row);
_Default.NameList.AcceptChanges(); // I've tried with and without this.
}
I've tried saving them to GridView control but that seems like quite a bit of work.
I'm new to ASP.Net but have done windows programming in C# for the last two years.
You're creating a new DataTable object each time the page loads.
You need to persist the DataTable object to session state or a static variable, or save the data to a database.
Remember that handling events like your button click requires a full postback. You don't run just the click code, you run your entire page lifecycle on a new instance of your page class. The new instance of your page class means a new instance of the datatable as well.
The issue here is that your DataTable is being created every time your page loads and it goes out of scope when your page has finished loading and been displayed to the user. To get your desired effect, you will need to store the DataTable in either Session, ViewState, cache, use a control like GridView that will automatically store the underlying data in its state, or something else.
Since you're new to ASP.NET, check out your options for state management.

Resources