ASP.Net: Getting DataKey from GridView on Edit and Delete - c#

I am using a GridView control which is databound to a List of objects returned from a utility method. The GridView control has one of the columns set as its DataKey. When a row is Selected, it fires the Selected event handler and I can use myGridView.SelectedDataKey.Value to get the value of the DataKey column for the selected row.
However, the event handler for when a row is Edited or Deleted does not seem to have a mechanism to get the DataKey value for the row in question. The event arg parameter for these event handlers contains the index of the row in the GridView but I'm specifically after the DataKey value.
Re-obtaining the List of objects via the utility method along with the index obtained from the event arg parameter is not an option because the List of objects may have changed.
Can anyone tell me how I can do this?
TIA

protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)grdQuestions.DataKeys[e.RowIndex].Value;
}

protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
int i;
Con.Open();
cmd = new SqlCommand("USP_REGISTER", Con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#P_CH_ACTION_CODE", "D");
for ( i = 0; i <= grdApplication.Rows.Count - 1; i++)
{
CheckBox Ck=grdApplication.Rows[i].FindControl("cbItem") as CheckBox;
if (Ck.Checked==true)
{
int Id = (int)grdApplication.DataKeys[i].Values["INT_ID"];
cmd.Parameters.AddWithValue("#P_INT_ID", Id);
SqlParameter StrOut = new SqlParameter();
StrOut = cmd.Parameters.AddWithValue("#P_MSG_OUT", "out");
StrOut.Direction = System.Data.ParameterDirection.Output;
cmd.ExecuteNonQuery();
StrRetVal = (string)cmd.Parameters["#P_MSG_OUT"].Value;
}
Con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

here's my solution:
in the gridview set the DataKeyNames="id". this way the row will have a datakey
then in Grd_RowDataBound add an attribute to the button like this:
LinkButton Btn= (LinkButton)e.Row.FindControl("BtnDelete");
if (Btn!= null)
{
Btn.Attributes.Add("ROW_INDEX", e.Row.RowIndex.ToString());
}
then in the OnClick event use this:
int rowIndex= Convert.ToInt32(((LinkButton)sender).Attributes["ROW_INDEX"].ToString());
int id= Convert.ToInt32(Grd.DataKeys[rowIndex].Value);
and you got the datakey value in the gridview's postbacks.

You could use the index number returned from the Edit/Delete event and then select the row manualy
String yourDataKey = GridView.DataKeys[e.NewSelectedIndex].Item["youfield"].tostring();

Related

how to sum the column which is in the dataset and display in the footer

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
int IndexTypeID = 5;
mobjORACLE = new DatabaseObjects.OracleDBCalls();
DataSet dsetPortfolio = mobjORACLE.GetORACLEDataSet(IndexTypeID, "v_indextypeid", "cv_1", "fn_getportfolio");
if (dsetPortfolio.Tables[0].Rows.Count > 0)
{
ViewState["gvPortfolio_DataSource"] = dsetPortfolio.Tables[0];
gvPortfolio.DataSource = dsetPortfolio.Tables[0];
gvPortfolio.DataBind();
gvPortfolio.Visible = true;
//dsetPortfolio.Tables[0].Rows[0]["cashreserve"];
//ViewState["gvPortfolio_DataSource"] = gvPortfolio.DataSource;
gvPortfolio.Attributes.Add("bordercolor", "#999966");
}
}
catch (Exception ex)
{
throw ex;
}
}
}
In gvPortfolio i got a datatable which has a column by name amount allocated. Now the question is, i need to sum up the column and display its result in the footer. Can somebody help me out in getting out of this.
You would use the GridView.RowDataBound Event.
Excerpt from Microsoft Documentation:
Before the GridView control can be rendered, each row in the control
must be bound to a record in the data source. The RowDataBound event
is raised when a data row (represented by a GridViewRow object) is
bound to data in the GridView control. This enables you to provide an
event-handling method that performs a custom routine, such as
modifying the values of the data bound to the row, whenever this event
occurs.
For example:
void gvPortfolio_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
// Once you know you are in the footer row
// the sender object is the GridView and you can get the datasource
// loop thru the datatable adding up the values you want
// For example: let say column 3 have the number
// **** code is not tested - writing from memory ***
int total = 0;
int column = 3;
foreach(DataRow row in (DataTable)(sender.DataSource).Rows)
{
if (!row.IsNull(column))
{
// probably need more checking to make sure we have a valid integer
total += Convert.ToInt32(row[column]);
}
}
e.Row.Cells[column].Text = total.ToString();
}
}
Good morning I believe that this previous post should help you with what you are trying to accomplish.

How to add ListItem to DropDownList from code and get the selected value

I succeeded adding List-items to my DropDownList from my database, but after I ran my application and selected a value from the DropDownList, I checked my break point at code and I saw that the selected value is wrong. It always selects the first value.
My code is:
UserBLL uBLL = new UserBLL();
List<Item> list = uBLL.GetAllItemsCategory();
foreach (Item item in list)
{
int var = 1;
ListItem lItem = new ListItem(item.name, var.ToString());
modelsList.Add(lItem);
var++;
}
DropDownList2.DataSource = modelsList;
DropDownList2.DataBind();
How can I fix it so that when the following is executed I'll get the right selection and not just the first item?
order.nameItem = DropDownList2.SelectedValue;
You need to check for !IsPostBack in the Page_Load event, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Put logic here to bind
DropDownList2.DataSource = modelsList;
DropDownList2.DataBind();
}
}

delete from gridview using checkboxs

hi gusy im trying to anderstand how delete from database using grindview with checkboxs but i dont know why deleteresults.text and DeleteResults.Visible dont work this is my code (im new in programming :) and thx for your answers
protected void Button3_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;
// Iterate through the Products.Rows property
foreach (GridViewRow row in Products.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("selector");
if (cb != null && cb.Checked)
{
// Delete row! (Well, not really...)
atLeastOneRowDeleted = true;
// First, get the ProductID for the selected row
int id_offre = Convert.ToInt32(Products.DataKeys[row.RowIndex].Value);
// "Delete" the row
DeleteResults.Text += string.Format("This would have deleted ProductID {0}<br />", id_offre);
}
}
// Show the Label if at least one row was deleted...
DeleteResults.Visible = atLeastOneRowDeleted;
}
Have you set the DataKeyNames property on your GridView? You need to do that to use DataKeys[index]. According to MSDN, when you set the DataKeyNames property, the DataKeys object gets populated. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys(v=vs.100).aspx. Try setting that property, read more on that on MSDN.

oldvalues of SqlDatasource for dynamic gridview-templates

For a dynamic Gridview i am generating columns at runtime like this:
TemplateField tf = new TemplateField();
tf.HeaderText = colName;
tf.ItemTemplate = new GenericItem(ListItemType.Item, colName, "Command");
tf.EditItemTemplate = new GenericItem(ListItemType.EditItem,
Gridview1.Columns.Add(tf);
The GenericItem implements IBindableTemplate:
public class GenericItem : IBindableTemplate
This works fine, but when i am trying to update some columns, i need to have access to the old values. I assumed i could just use this:
<asp:SqlDataSource runat="server" ID="dsGridview" OldValuesParameterFormatString="old_{0}" ConflictDetection="CompareAllValues" />
But when i want to access the oldvalues property of my datasource in the RowUpdating event of the Gridview i noticed that the oldvalues collection is empty (the newvalues collection is filled just fine)
Does anybody know how i can get those oldvalues?
Best regards,
r3try
ok, this is not how i wanted to solve it - but as there are no other suggestions here is how i worked around my problem. Maybe someone else has the same problem:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//GET THE OLD VALUES
myOldValues.Clear();
GridView gv = (GridView)sender;
gv.EditIndex = e.NewEditIndex;
gv.DataBind();
//populate
for (int i = 0; i < Gridview1.Columns.Count; i++)
{
DataControlFieldCell cell = gv.Rows[e.NewEditIndex].Cells[i] as DataControlFieldCell;
gv.Columns[i].ExtractValuesFromCell(myOldValues, cell, DataControlRowState.Edit, true);
}
Session["MyOldValues"] = myOldValues;
}

Get the deleted row's index in a DataGridView

I deleted a row in my DataGridView by selecting it and pressing Delete and would like to get the row's index. How could i do that?
You may obtain an index before you delete a row by handling UserDeletingRow event.
dataGridView1.UserDeletingRow += (sa, ea) =>
{
MessageBox.Show(ea.Row.Index.ToString())
};
You can get the selected index of the current selected item:
int index = DataGrid1.SelectedIndex;
You can do this before deleting the item and you will know the index.
Most of the answers in StackOverflow mentioned UserDeletedRow as an event to handle and get the user deleted row index. this event only fired after deleting that row.
The correct one must be UserDeletingRow, where by this event you can do something before you lose the deleted row.
Now how to get the row index? the answer by using the below code
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
int tmp = e.Row.Index;
}
Maybe this will help you.
private void EvtBindingNavigatorDeleteItemClick(object sender, System.EventArgs e)
{
ToolStripButton MyToolStripButton = (ToolStripButton)sender;
CustomBindingNavigator MyCustomBindingNavigator =
(CustomBindingNavigator)MyToolStripButton.GetCurrentParent();
CustomDataGridView MyDataGridView = GetDataGridView(MyCustomBindingNavigator);
int RowIndexDelete = -1;
BindingSource MyBindingSource = MyCustomBindingNavigator.BindingSource;
DataTable MyDataTable = (DataTable)MyBindingSource.DataSource;
foreach ( DataRow MyDataRow in MyDataTable.Rows)
{
if (MyDataRow.RowState == DataRowState.Deleted)
RowIndexDelete = MyDataTable.Rows.IndexOf(MyDataRow);
}
}

Categories