How to get the AppId from gridView in codebehind, if I clicked the edit image button in second row.
Aspx Code:
<asp:BoundField HeaderText="AppId" DataField="AppID" />
<asp:TemplateField HeaderText="Actions" ControlStyle-Width="20px" ItemStyle-Width="130px">
<ItemTemplate>
<asp:ImageButton ID="imgMailCamp" runat="server" ImageUrl="~/Images/AppSetup/Mail.png"
Height="18px" ToolTip="Send Mail Campaign" CssClass="grdImageAlign" CommandName="SendMail" OnClick="btnMailCamp_Click" />
<asp:ImageButton ID="imgViewApp" runat="server" ImageUrl="~/Images/AppSetup/application-view-list-icon.png"
Height="18px" ToolTip="View Appplication" CssClass="grdImageAlign" CommandName="View" OnClick="btnView_Click" />
<asp:ImageButton ID="imgEditApp" runat="server" ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign" CommandName="Edit" OnClick="btnEdit_Click"/>
<asp:ImageButton ID="imgDeleteApp" runat="server" ImageUrl="~/Images/AppSetup/Trash-can-icon.png"
Height="18px" ToolTip="Delete Application" CssClass="grdImageAlign" CommandName="Delete" OnClick="btnDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
C# Code:
protected void btnEdit_Click(object sender, EventArgs e)
{
// I need to get the current row appId, I use this appId in next page for sql query
Response.Redirect("/Secured/EditApplication.aspx?AppID="+AppID);
}
Try Like this....Don't Define Click Event of Button....Define Button Like this...
<asp:ImageButton ID="imgEditApp" runat="server"
ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign"
CommandName="Edit"/>
And
Define Your GridView RowEditing event Like this....
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
Response.Redirect("/Secured/EditApplication.aspx?AppID="+YourGridViewId.Rows[e.NewEditIndex].Cells[1].Text);
}
Edit:
I think you have problem in definig RowEditingEvent.....ok you can do this...nothing to change just write this code in you Click event...
protected void btnEdit_Click(object sender, EventArgs e)
{
ImageButton ib = sender as ImageButton;
GridViewRow row = ib.NamingContainer as GridViewRow;
Response.Redirect("/Secured/EditApplication.aspx?AppID="+YourGridViewId.Rows[row.RowIndex].Cells[1].Text);
}
Edit 2
<asp:ImageButton ID="imgEditApp" runat="server"
ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign"
CommandName="Edit" CommandArgument='<%#Eval("AppID") %>'/>
protected void btnEdit_Click(object sender, EventArgs e)
{
string appid= (sender as ImageButton).CommandArgument;
Response.Redirect("/Secured/EditApplication.aspx?AppID="+appid
}
You can get grid view cell value from this.
GridView.Rows[RowIndex].Cells[CellIndex].Text
Here "RowIndex" is row number from which you want to get data and "CellIndex" is cell number from which you want to get data.
I think event "OnRowCommand" of gridview is best suited for your problem.
use blow link for more details
http://www.codeproject.com/Tips/564619/Example-of-gridview-rowcommand-on-Button-Click
it should be with commandargument
aspx
<asp:ImageButton ID="imgEditApp" CommandArgument='<%# Eval("AppID") %>' runat="server" ... OnClick="btnEdit_Click"/>
code
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
int categoryId = Convert.ToInt32(e.CommandArgument);
Response.Redirect("/Secured/EditApplication.aspx?AppID="+categoryId);
}
or u can use PostBackUrl property of imagebutton and it would be like this:
<asp:ImageButton ID="imgEditApp" PostBackUrl='<%# string.Format("/Secured/EditApplication.aspx?AppID={0}", Eval("AppID")) %>' runat="server" />
Check this code snippet.
This is the code in aspx file having two columns DataBound "AppId" and TemplateColumn "Action" containing Image Button. Observe CommandName and CommandArgument properties of Image Button. Also Define OnRowCommand Event listener for gridview.
<asp:GridView ID="grdDisplayData" runat="server" AutoGenerateColumns="false"
EnableViewState="false" onrowcommand="grdDisplayData_RowCommand">
<Columns>
<asp:BoundField HeaderText="AppId" DataField="AppId" />
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="MyEdit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex%>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageAction">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Width="15px" Height="15px"
CommandName="ImgEdit" CommandArgument="<%# ((GridViewRow) Container).RowIndex%>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is the code behind code. The e.CommandArument returns the index of the row in which the image button was clicked.
protected void grdDisplayData_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "ImgEdit")
{
int RowIndex = Convert.ToInt32(e.CommandArgument);
Response.Redirect("/Secured/EditApplication.aspx?AppID=" + grdDisplayData.Rows[RowIndex].Cells[1].Text.Trim());
}
}
Let me know if this fixed your problem.
Cheers!!!
Piyush Deshpande
Related
I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}
I am having textboxes and buttons in gridview. What I want is that when I click on those buttons the corresponding value in textbox is updated to database, so I need to access the textbox text in OnClick event. How can I do this?
Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="#CCCCCC" BorderColor="#999999"
BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2"
ForeColor="Black" OnRowDataBound="GridView1_RowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Save 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" Width="30px" runat="server"></asp:TextBox>
<asp:Button ID="btnSave1" runat="server" Text="Save" OnClick="btnSave1_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Save 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" Width="30px" runat="server"></asp:TextBox>
<asp:Button ID="btnSave2" runat="server" Text="Save" OnClick="btnSave2_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Button Onclick Event:
protected void btnSave1_Click(object sender, EventArgs e)
{
//I want to access TextBox1 here.
}
Please help me out of this.
You can do like this:
protected void btnSave1_Click(object sender, EventArgs e)
{
GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
TextBox TextBox1 = row.FindControl("TextBox1") as TextBox;
//Access TextBox1 here.
string myString = TextBox1.Text;
}
Basicly this is an example of how to get the TextBox value:
string CustomerID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCustomerID")).Text;
In my grid view there is a LinkButton and I have defined CommandName="Download" CommandArgument='<%#Eval("FileID")%>' for the LinkButton, but I do not know how to find click event for the Link Button? please help how I can code for this LinkButton with using e. CommandName
<asp:GridView ID="GridViewEfile" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#000000" GridLines="Both" DataKeyNames="FileID">
<AlternatingRowStyle BackColor="Yellow" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick = "Retreive_file" CommandName="Download" CommandArgument='<%#Eval("FileID")%>'><%#Eval("FileName")%></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You don't have to use Click and Command events together. Command is enough.
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
// Do something with e.CommandName or e.CommandArgument
}
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Command"
CommandName="Download" CommandArgument='<%#Eval("FileID")%>'>
You need to get rid of the click event OnClick = "Retreive_file" on button. has no meaning here
public void GridViewEfile_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
// here goes your code
}
}
Remove OnClick = "Retreive_file"
<asp:GridView ID="GridViewEfile" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewEfile_OnRowCommand" CellPadding="4" ForeColor="#000000" GridLines="Both" DataKeyNames="FileID">
<AlternatingRowStyle BackColor="Yellow" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%#Eval("FileID")%>'><%#Eval("FileName")%></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and use function
public void GridViewEfile_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
//you can get your command argument values as follows
string FileId=e.CommandArgument.ToString();
}
}
I have a ASP:grid which has a link button, i need to some how reference that on the code behind when its clicked but im struggling on the syntax
Heres my ASP:Grid i need to execute code in the code behind when that link button 'Re-Take' is pressed and also be able to know what row it was clicked on as i will need to reference the users emails and name and then send an email with the relevant information....
<asp:GridView ID="GrdViewUsers" runat="server" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" class="tablesorter">
<AlternatingRowStyle></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Re-Take" runat="server" ID="Edit" CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Full Name">
<ItemTemplate>
<asp:HyperLink ID="HyperFullName" CssClass="gvItem" runat="server" NavigateUrl='<%#Eval("UserID","/ExamPaper.aspx?uid={0}") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.FullName") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblSurname" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DateTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Total">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTotal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If someone can help me with a snippet i would highly appreciate it
You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.
To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.
<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />
where myObjectID is the name of the ID column of your object you bind the grid to.
Then
void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
if ( e.CommandName == "LinkButtonClicked" )
{
string id = e.CommandArgument; // this is the ID of the clicked item
}
}
see: ASP.net GridView: get LinkItem's row
FindControl should work in this case.
protected void GrdViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("Edit") as HyperLink;
}
}
First: You have repeating ID's in your TemplateFields like lblUsername what is not allowed since it's the same NamingContainer.
You can pass the RowIndex as CommandArgument to RowCommand:
on aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
Text="Re-Take"
runat="server"
ID="Edit"
CommandName="Edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Handle the GridView's RowCommand:
void GrdViewUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GrdViewUsers.Rows[index];
// now you can get all of your controls like:
Label lblSurname = (Label)row.FindControl("lblSurname");
String email = lblSurname.Text // you noticed that DataItem.Email is bound to lblSurname?
}
}
Suppose the grid has linkbutton on which we want to get row index
<asp:LinkButton ID="lnkbtnAdd " runat="server" CommandName="cmdAdd" ImageUrl="~/Images/add.gif" ></asp:LinkButton>
In code behind, In OnRowCreated event we attach row number of grid to each button of row to get it back when it is clicked in RowCommand event
protected void gvListing_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.LinkButton lnkbtnAdd = new System.Web.UI.WebControls.LinkButton();
lnkbtnAdd = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lnkbtnAdd");
if (lnkbtnAdd != null)
lnkbtnAdd .CommandArgument = e.Row.RowIndex.ToString();
}
}
In RowCommand event we will get back the current row index and set the selected index of the grid
protected void gvListing_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "cmdAdd")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());// Current row
}
}
I am trying to update the value of ajaxrating control and comments in the database`
` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id"
onrowdatabound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="PurchasedPID" DataField="PurchasedPID"/>
<asp:BoundField HeaderText="DatetimePurchased" DataField="orderdate" />
<asp:BoundField HeaderText="MMBName" DataField="MMBName" />
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true" AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5"
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved" CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text= '<%# Bind("Comments") %>' multiline="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So I added the following rowcommand event on of the members suggestion.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Submit")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
TextBox TextComments = row.FindControl("TextBox1") as TextBox;
string comments = TextComments.Text;
objBLL.UpdateRating(ratingScore, Id,comments);
}
But here instead of getting the new rating, it is inserting the CurrentRating in the table.
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
I think its because of this CurrentRating here.
Any idea how to get the value of updated rating? Or should i use an additional Rating_changed event to update the rate, and then a row command event to update the comments
Thanks
Sun
The easiest way to bind the your DataKey/ItemID to the Tag attribute of the Rating control
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true"
AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5" **Tag='<%# Bind("id")%>'**
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved"
CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
Event Handler
protected void Rating2_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
Rating r = sender as Rating;
int id = Convert.ToInt32(r.Tag);
objBLL.UpdateRating(Convert.ToInt32(e.Value),id)
}
You can use GridView1_RowCommand to update rating score in the DB. e.g.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Rating")
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
}
}
Set CommandName="Rating" to your linkbutton
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Rating">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>