Deleting a row in datagrid view - c#

I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.
A sample code is appreciated.
Thanks

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
String productId = row.Cells[0].Text; // I suposed your product Id in very first column in gridview
//Delete Code goes here..........
...........................
}
}

you can use RowCommand event of gridview, like...
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
e.CommandArgument -- this return Data Key Value
//Deletion Code goes here.....
var brochureToDelete = (from b in dataContext.ArticleBrochures where b.ArticleId == ArticleId select b).FirstOrDefault();
if (brochureToDelete != null)
{
dataContext.ArticleBrochures.DeleteOnSubmit(brochureToDelete);
dataContext.SubmitChanges();
bindBrochureGridView(ArticleId);
// if your gridview in updatepanel
//Call update method of UpdatePanel
//UpdatePanel.Update();
}
}

Set PK_ID to link button's command args like that
<asp:LinkButton runat="server" ID="btn_manage" Text="Delete" CommandArgument='<%#Eval("PK_ID") %>'
OnCommand="btn_manage_click">
</asp:LinkButton>
and access this PK_ID on event
protected void btn_manage_click(object sender, CommandEventArgs e)
{
string ID = e.CommandArgument.ToString();
//you delete code and gridview bind code
}

bind the linkbutton id as the primary key. On client clicking the link button save that id in a hidden field. This hidden field value will be the id of row to be deleted.
Then on the server click of link button delete the row corresponding to the hidden field value

I presume you have a method which sends a delete query.
Make a RowDeleting event handler, pass your row index using e.RowIndex to the delete method.
Use this e.RowIndex to write a query to delete the 'n'th row of your table. and then bind the data to your gridView.

Related

C# - Gridview Help. (ASP.NET)

I have a gridview that pulls data from local SQL server. I chose 3 columns to be displayed on the gridview. I added a fourth column (select command). I would like to get the data from the first column which is an id when I click the select command but i always get an error "An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection."
Basically I would like to get the id from the first column then assign it to a session variable then redirect to a second page and then use the content of that session variable to populate another textbox.
protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = grdClients.Rows[grdClients.SelectedIndex].Cells[0].Text.ToString();
Session["ID"] = id;
Response.Redirect("secondPage.aspx");
}
Any suggestions?
Thanks
1- add attribute to the GridView
DataKeyNames="aboutusID"
2- add a templatefield to your columns
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="SelectSession" Text="EDIT" CommandArgument='<%# DataBinder.Eval(Container,"RowIndex")%>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
3- in your code behind
protected void GridViewAbout_RowCommand(object sender, GridViewCommandEventArgs e)
{
// this to skip on paging or sorting command
if (e.CommandName != "Sort" & e.CommandName != "Page")
{
// Get the command argument where the index of the clicked button is stored
int index = Convert.ToInt32(e.CommandArgument);
// Get the data key of the index where the id is stored
int id = Convert.ToInt32(GridViewAbout.DataKeys[index].Value);
if (e.CommandName == "SelectSession")
{
// Your Code
}
}
}
i think you should use the SelectedIndexChanged event for that.
Then you assign the GridviewRow property to the selected row "GridViewRow row = grdClients.SelectedRow;"
After that you can use row to get the value of the first cell and assign it to your session or where ever you want. "row.Cells[0].Text;"
protected void grdClients_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdClients.SelectedRow;
string id = row.Cells[0].Text;
Session["ID"] = id;
Response.Redirect("secondPage.aspx");
}
Thank you everyone,
I was able to come up with a solution by taking pieces from every solution you provided. Thanks very much.
Below is my solution:
protected void grdClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = grdClients.Rows[index].Cells[0].Text.ToString();
Session["ID"] = id;
Response.Redirect("secondForm.aspx");
}
}

Get a hidden field in Gridview on RowCommand Event

If I have two buttons on gridview and each performing different function. For example my code below,
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
errorlab.Text = row.Cells[3].Text;
}
}
The value of cell 3 is a hidden field and there is a value in the database that's binding to hidden field but with my code I couldn't get the value. The errorlab label is showing nothing. Maybe I'm missing something.
I would like to suggest an answer, the command argument will not fetch you the row index. Instead it will give you what you bind during gridview data binding.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Do something else
}
else if (e.CommandName == "View Cert")
{
//The hidden field id is hdnProgramId
HiddenField hdnProgramId = (((e.CommandSource as LinkButton).Parent.FindControl("hdnProgramId")) as HiddenField);
}
}
This will try to locate the hidden field from the gridview row context.
If you have futher controls on the gridview cell then you have to access them using the Controls property
HiddenField hiddenField =row.Cells[3].Controls[0] as HiddenField;
if(hiddenField != null)
errorlab.Text = hiddenField.Value;
You have to use the correct index for the controls. Debug the code and check what is position of the control in row.Cells[3].Controls.
Always try to avoid referring cells by it's index position in gridview as it may result in changing the code if you happen to add/delete few more columns in the grid in the future which might result in undesired result. Also note that hiddenfield does not have a Text property but rather a Value property to access it's value.
If you know the hiddenfield's name then better try accessing it by it's name. Let's say you have your hiddenfield defined as below in your gridview
<ItemTemplate>
<asp:HiddenField ID ="hdnField" runat="server" Value='<%# Bind("ErrorLab") %>'/>
</ItemTemplate>
Then in your GridView1_RowCommand you can do
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
HiddenField hdnField = (HiddenField)row.FindControl("hdnField");
errorlab.Text = hdnField.Value;

Disable button in Gridview in multiple pages

I have buttons in one Column called Type. When the user clicks on the button it should be disabled. This works fine in the first page but it doesnt on the second,third,fourth pages.
I have 10 rows in my page and e.CommandArgument gets the row number.
I believe the buttons are populated in the gridview from 0 to 9 and e.CommandArgument is 1-10. Thats why I have (e.CommandArgument) - 1 and it works find in the first page.
The things that in the second page the next buttons are again 0-9 but my e.CommandArgument is 11-20. Any ideas?
protected void GridViewType_RowCommand(object sender, GridViewCommandEventArgs e)
{
Button btnVote = (Button)GridViewType.Rows[Convert.ToInt32(e.CommandArgument) - 1].FindControl("btnVote");
btnV ote.Enabled = false;
}
try the following
protected void GridViewType_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)(e.CommandSource);
Button btnVote = (Button)row.FindControl("btnVote");
btnVote.Enabled = false;
}
kindly check this :
want to Find Control in gridview on RowCommand event

trigger an eventhandler on postback c#

I am pretty new to c# programming.
I have an issue that follows:
I have a GridView on a web form, a DropDownList and a Label control. When i select a value from a DDL a Grid View is populated with rows from the database that equal the DDL condition(in my case DDL represent Countries, GV lists the Cities).
When i delete the last City from a GV using a built in GV Delete function i would like to automatically write in a Label that there are no more Cities in selected Country.
How can i achieve that?
I tried to put
protected void GridView1_RowDeleted1(object sender, GridViewDeletedEventArgs e)
{
if (GridView1.Rows.Count == 0)
{
LabelGrid.Text = "No more cities.";
}
}
but it didn't work.
Thanks for your help
Consider using PreRender event, when that event runs the Row.Count property contains the correct value. (decremented after delete)
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0)
{
LabelGrid.Text = "No more cities.";
}
}

How to determine which row is clicked in GridView using c#

I have a GridView1 in my form which populate a table from my Database.
The columns in my table are
ID NAME EMAIL ADDS
Now I want a user to click on ID Row and show a message in a label which row is clicked by a user. How can I do this? I've been googling for a long time.
You can find out the clicked row/column in the DataGridView.CellClick Event Handler.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// e.RowIndex
// e.ColumnIndex
}

Categories

Resources