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();
}
}
Related
I have a status column which includes approved, rejected or cancelled. I have another Actions column which contain link buttons approve and reject. Now if the status is Cancelled, I want the link button to be disabled for that row.
I tried to use GridView1_DataBound event but couldn't figure out the logic.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Server.HtmlDecode(e.Row.Cells[0].Text.Trim()).Equals("Cancelled"))
{
//OR you can disable it instead of complately hiding it
((LinkButton)GridView1.Rows[e.Row.RowIndex].Cells[0].Controls[0]).Enabled = false;
}
}
}
Method A
The following should work:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton runat="server" Enabled='<%# !(Eval("Status").ToString().Equals("Cancelled")) %>'>Approve</asp:LinkButton>
<asp:LinkButton runat="server" Enabled='<%# !(Eval("Status").ToString().Equals("Cancelled")) %>'>Reject</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Method B
Nevertheless, if you do insist on the code-behind approach the safest way to access the LinkButton controls is the following:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="ApproveButton" runat="server">Approve</asp:LinkButton>
<asp:LinkButton ID="RejectButton" runat="server">Reject</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text.Equals("Cancelled"))
{
((LinkButton)e.Row.FindControl("ApproveButton")).Enabled = false;
((LinkButton)e.Row.FindControl("RejectButton")).Enabled = false;
}
}
}
Explanation
Your code doesn't work because the LinkButton controls are not placed in the cell's Controls collection in the way you're expecting them to. Find out yourself by placing a breakpoint inside the inner condition of GridView1_RowDataBound and check out the items of the Controls collection. You'd be surprised!
Maybe you can use this code
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="gridView_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Column1" DataField="Column1" />
<asp:BoundField HeaderText="Column2" DataField="Column2" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%#Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="lnkAction" runat="server">Approve</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var status = (e.Row.FindControl("lblStatus") as Label).Text;
if (status == "Cancelled")
{
(e.Row.FindControl("lnkAction") as LinkButton).DisableControl("Disabled button.");
}
}
}
And to disable the button you can use an extension method
public static class Extensions
{
public static TControl DisableControl<TControl>(this TControl control, string desableMessage) where TControl : WebControl
{
control.Attributes.Add("disabled", "");
control.Attributes.Add("data-toggle", "tooltip");
control.Attributes.Add("title", disableMessage);
control.Enabled = false;
return control;
}
}
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 have a system that adds items into the DataGrid, my question is how can i use the delete button? when the user wants the item deleted, user will press the button to delete the row, but i cant seem to make it work. thank you!
<asp:GridView runat="server" ID="gridview" CssClass="table-hover" AutoGenerateColumns="true" HeaderStyle-BackColor="CornflowerBlue" BackColor="White" BorderWidth="5" BorderColor="CornflowerBlue" OnSelectedIndexChanged="gridview_SelectedIndexChanged" CellPadding="8"
CellSpacing="0" Width="100%" OnRowDeleting="gridview_RowDeleting" EmptyDataText="No records to display">
<HeaderStyle BackColor="CornflowerBlue"></HeaderStyle>
<Columns>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" />
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="lnkEdit" runat="server" ImageUrl="~/Images/Icons/Modify.png" OnClick="Edit" />
<%--<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my script
<script runat="server">
void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gridview.Rows[e.RowIndex].Cells[2];
}
</script>
grid view picture
In Gridview add OnRowCommand="gridview_RowCommand"
CommandField can work but I go like this:
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:Button ID="lnkDel" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
In code behind
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del") {
//Get Command Argument
int IdToDelete = Convert.ToInt32( e.CommandArgument.ToString());
//Your Delete Command
//Rebind GridView
}
}
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
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>