I am using a CommandField Delete imagebutton but it does not work. here is a snippet which i have tried:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int indx = row.RowIndex;
using (Property_dbDataContext context = new Property_dbDataContext())
{
if (e.CommandName == "Delete")
{
var delete = (from a in context.Property_basics where a.prop_id == GridView1.Rows[indx].Cells[0].Text select a).Single();
delete.delete_status = 1;
context.SubmitChanges();
GridView1.DeleteRow(indx);
}
}
}
.aspx:
<asp:CommandField ButtonType="Image" HeaderText="Delete" DeleteImageUrl="~/wp-content/themes/realia/assets/img/500px-Delete_Icon2.png" ShowDeleteButton="True" />
the exception which it shows is:
Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type
'System.Web.UI.WebControls.GridViewRow'.
Instead of searching the row you should use the CommandArgument to get the RowIndex. In the case of a CommandField the CommandArgument is the RowIndex. In the case of the CommandArgument passed on a standard control it's the actual command argument.
int rowIndex = int.Parse(e.CommandArgument);
GridViewRow row = GridView1.Rows[rowIndex];
try this:
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer.Parent.Parent;
Or Like
Setting Command Arguments
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = ProductsGridView.Rows[index];
Your ASPX will look like this :
<asp:Gridview id = Gridview1 runat = "server" DataKeyNames="ID" >
Code Behind : You can do it like this,
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = Convert.ToInt32(dg1.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)dg1.Rows[e.RowIndex];
// write your code. to delete
}
Related
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 ;
}
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
I want to be able to enable/disable a textbox inside gridview. I have case statement and in my case statement when Case = 1 then I want to disable a texbox called txtType in my gridview. Here is my code:
SqlDataAdapter da = new SqlDataAdapter(#"select * from my table ", con);
DataTable dtTable = new DataTable();
da.SelectCommand.Parameters.AddWithValue("#RSP_SET_SK", (RSP_SET_SK));
da.Fill(dtTable);
GridView1.DataSource = dtTable.DefaultView;
GridView1.DataBind();
DataRow dtTable_row = dtTable.Rows[0];
if (dtTable.Rows.Count > 0)
{
DDL_TYPE.SelectedValue = dtTable_row.Field<string>("TYPE").ToString();
ddlPr.SelectedValue = dtTable_row.Field<Int32>("ID").ToString();
}
DataRow row1 = dtTable.Rows[0];
int temp = Convert.ToInt32(row1["STATUS"]);
switch (temp)
{
case 1:
lblStatus.Text = temp + " - Initial Test.";
break;
}
You can do this in RowDataBound event. First, make sure you set OnRowDataBound property in the aspx code like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
Then add the following in code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView data = (DataRowView)e.Row.DataItem;
TextBox txtType = (TextBox)e.Row.FindControl("txtType");
int status = Convert.ToInt32(data["STATUS"]);
if (status == 1)
{
txtType.Enabled = false;
}
}
}
Since it is in a gridview, you will need to use this..
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
string type = ((TextBox).gvr.FindControl("txtType"));
Then to disable or enable you can use..
type.Enabled = true;
I hope that gives you the general idea how to do it.
Edit: You might need to use a foreach loop.
foreach(GridViewRow gvr in GridView1.Rows)
{
string type = ((TextBox).gvr.FindControl("txtType"));
type.Enabled = true/false;
}
This should do it I would imagine. I do use this foreach pretty often in one of my applications.
Edit 2:
I just realized I put a period where it should not. My bad. So it should be this.
string type = ((TextBox)gvr.FindControl("txtType"));
or
TextBox type = ((TextBox)gvr.FindControl("txtType"));
or you can just enable it straight up like this..
((TextBox)gvr.FindControl("txtType")).Enabled = true/false;
You should do this in RowDataBound Event. Below link has sample code which can help you.
Reference
a TextBox into a GridView
<asp:GridView ID="mygrid" runat="server">
<Columns>
<asp:TemplateField meta:resourcekey="TemplateFieldResource4">
<ItemTemplate>
<asp:TextBox ID="mytextBoxID" runat="server" Text="0,00" Enabled="false" />
</ItemTemplate>
<HeaderStyle Width="10%" HorizontalAlign="Right"/>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void any_Click(object sender, EventArgs e) {
foreach (GridViewRow gvr in gvData.Rows)
((TextBox)gvr.FindControl("mytextBoxID")).Enabled = true;
}
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>
Hallo there
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView I have a regular Button control to which I added some code like this.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "addToSession")
{
//get the row index stored in the CommandArgument property
int index = Convert.ToInt32(e.CommandArgument);
//get the gridview row where the command is raised
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//values stored in the text property of the cells
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why.
I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>'
runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Advice perhaps as to what to do
regards
ImageButton.CommandName is a valid property and it should work the same as Button.CommandName.
The problem, then, is most likely in your GridView1_RowCommand procedure. Can you post the entire procedure code including the part intended to handle the ImageButton click?