How to delete a row without using OnRowDeleted/OnRowDeleting in gridview - c#

Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??

As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}

Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you

Related

how to find button inside gridview

i have gridview in my project and there is one button inside that gridview.
i want to change that button's property according to gridview cell value
below is my gridview with button
<div class="row">
<div class="col-md-12">
<h1 style="color:red" id="payDetailH" runat="server" visible="false">Payment Details</h1>
<br />
<asp:Panel ID="Panel2" runat="server" ScrollBars="Auto">
<asp:GridView ID="gvPayemenDetailNew" CssClass="table table-hover" GridLines="None" runat="server"
OnRowCommand="gvPayemenDetailNew_RowCommand" OnRowDataBound="gvPayemenDetailNew_RowDataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnGenNew" runat="server" CommandName="GJobID" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Ceate Job" CssClass="btn" Enabled="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="50px" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
</asp:Panel>
</div>
</div>
and this is my code behind
protected void gvPayemenDetailNew_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow row in gvPayemenDetailNew.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Button btn = e.Row.FindControl("btnGenNew") as Button;
if (PayStatus == "Approved")
{
btn.Enabled = true;
}
}
}
}
i got this error
System.NullReferenceException: Object reference not set to an instance of an object.
click here to see my screens
you must use [row] in loop :
protected void gvPayemenDetailNew_RowDataBound(object sender,
GridViewRowEventArgs e)
{
foreach (GridViewRow row in gvPayemenDetailNew.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Button btn = row.FindControl("btnGenNew") as Button;
if (PayStatus == "Approved")
{
btn.Enabled = true;
}
}
}
}
You don't need to loop the GridView in the RowDataBound event. It is already executing per row when data is bound to the GridView. And when in a loop you set all the buttons based on the last row value, not per row.
So this should be the correct way, assuming PayStatus is a column in the dataset bound to the GridView.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//find the button with findcontrol
Button btn = e.Row.FindControl("btnGenNew") as Button;
//use the paystatus of the current row to enable the button
if (row["PayStatus"].ToString() == "Approved")
{
btn.Enabled = true;
}
}
}
Everything looks really good in your code. This the correct way to find controls. Just one suggestion but not sure if its going to work, You can change the way you typecast the button
Button btn = (Button)e.Row.FindControl("btnGenNew");

How to get row data by clicking a image button in a row in an ASP.NET gridview

I have a GridView in a ASP.NET web application, in which I have added image button in each row:
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="edit" runat="server" CommandArgument='<%# Bind("EmpID") %>' CommandName="edituser" ImageUrl="image/images.jpg"
ToolTip="Edit User Details"> </asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
Now how I can get the row data from gridview simply by clicking an edit image button in a row?
You have to change the CommandArgument with this one:
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>
Then:
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "edituser") /*if you need this
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the buttonfrom the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here now you have the specific row data
}
}
Bind all the columns in the label control respectively, and you can get value using findcontrol method at GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Label _lblText = (Label)this.GridView1.SelectedRow.FindControl("UR_Desired_Label_ID");
this.TextBox3.Text = _lblText.Text ;
}

How to fetch values from cells inside Grid View

I have used grid view in my ASP.NET application.
<asp:GridView ID="grdView" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Jurisdiction">
<ItemTemplate>
<asp:Label ID="lblJurisdiction" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
in cs file
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
Note that the above grid will be populated by data. Now I need to get data from already populated gridview. The above code is not working. Also I need to retrieve from labels, textboxes, checkboxes values inside grid. Please help !!!
You can use FindControl method to retrieve the control's data:-
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
CheckBox chkbox = row.FindControl("chkbox") as CheckBox;
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
..and so on
//Finally retrieve the data like your normal control
string labelText = lblJurisdiction.Text;
}
}
Use GridViewRow.FindControl method.
foreach (GridViewRow row in grdView.Rows)
{
// return you the check-box control from current row
var chkbox = row.FindControl("chkbox");
}
Check whether the row type is DataControlRowType.DataRow.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
}
To get the TextBox, CheckBox value from the grid use this,
string TextBoxvalue = ((TextBox)GridViewID.Rows[i].FindControl("TextBoxName")).Text;
string CheckBoxvalue = ((CheckBox)GridViewID.Rows[i].FindControl("CheckBoxName")).Text;
In your code .cs file, you are missing to check only for datarow. As it will check all 3 places:-
1. Header
2. Body
3. Footer
Might any one place, any exception can occur.
Please add one more if condtion just after the for loop, as below.
if (row.RowType == DataControlRowType.DataRow)
{
Hope this post will help's you :).
Use
cells[i].EditedFormatedValue

How to get selected item from Dropdown in GridView?

I have a GridView. Whenever I'm clicking on the LinkButton after selecting the Dropdown value, I'm getting only the first item of the Dropdown.
I need to show the selected value in TextBox. How can i get the desired value ?
This is my pseudo code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EnableModelValidation="True"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Count">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="true" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Button">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Count", typeof(string));
dt.Rows.Add("A", "5");
dt.Rows.Add("B", "8");
dt.Rows.Add("C", "4");
dt.Rows.Add("D", "7");
dt.Rows.Add("E", "9");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
ddl.Items.Clear();
int count = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Count").ToString());
List<string> list = new List<string>();
for (int i = 1; i <= count; i++)
{
list.Add(i.ToString());
}
ddl.DataSource = list;
ddl.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
DropDownList ddl = (DropDownList)GridView1.Rows[grdrow.RowIndex].FindControl("DropDownList1");
TextBox1.Text = ddl.SelectedValue.ToString();
}
Thanks in advance...
I'm going to guess that you should implement INotifyProperty change with the databinding. This way every change will be recorded including those made after first change in the drop down box. see ~ http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Since you are dynamically creating and binding the Dropdownlist, it would not have loaded at the point your click event is executed. For you to use bound properties (the selectedValue property in this case), the control must already be loaded and it's viewstate info parsed and set by the control.
The databinding event that creates the dropdownlist runs after pre-render. See http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx for details on the page lifecycle.
To do what you are asking requires very close attention to the page life cycle. Try moving the code that sets the textbox to the GridView1_RowDataBound method. For this to work though, your control must be rendered with the same properties everytime (that way the event's on it are wired up correctly and the selectedValue property is set correctly).
Another alternative is to handle events on the textbox or dropdownlist itself. You would again have to pay attention to the properties and lifecycle of the control.
ASP.Net Forms uses the SmartUI pattern and IMHO this is the single greatest knock against this pattern.
Ok, try this
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lnkBtn = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnkBtn.NamingContainer;
DropDownList ddl= (DropDownList)row.FindControl("DropDownList1");
TextBox1.Text = ddl.SelectedValue.ToString();
}

Row index of LinkButton in GridView

I am using Link button as Template Field in GridView.
Now i want to display the row index of the Linkbutton clicked.
Please suggest me a solution Thanks in advance
suppose in Item Template this is ur link button
<ItemTemplate>
<asp:LinkButton ID="lnkapprove" Font-Underline="true" runat="server" Text="Approve" OnClick="lnkapprove_Click"></asp:LinkButton>
</ItemTemplate>
in Code Behind:
protected void lnkapprove_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int i = Convert.ToInt32(row.RowIndex);
}
you can get row.RowIndex like this..
Hope this helps..
Please try this one:
protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
}
You can also try this code in row bound event
GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
like this
protected void userGridview_RowBound(object sender, GridViewCommandEventArgs e)
{
GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
}
Use Container.DisplayIndex inside Page's gridview template. On code behind RowCommand handler, you'll have the row index as argument.
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="lbExample" runat="server" CommandName="DoAction" CommandArgument='<%# Container.DisplayIndex %>' ToolTip="Action link" CssClass="btn btn-sm btn-light"><i class="fa fa-edit"></i></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

Categories

Resources