Making values inside column clickable (fires click_event) - c#

I have a grid and I want to make the values in the first column "clickable" so that they fire a click event. The values in this first column are populated from a sql server query.
What would be the best way to accomplish this?
Below is my grid:
<asp:GridView runat="server" ID="HSMGrid"
AutoGenerateColumns="false"
DataKeyNames="Status"
OnRowCommand="grdvwSearchDepositTransaction_RowCommand" OnRowDataBound="grdSearch_RowDataBound" ShowHeaderWhenEmpty="true"
CssClass="grid" Width="550">
<Columns>
<asp:BoundField DataField="TransactionGroupsEntry.groupID" HeaderText="BatchID" ItemStyle-CssClass="mediumColumn columnCenter" />
<asp:BoundField DataField="TransactionGroupsEntry.bankNumber" HeaderText="Bank" ItemStyle-CssClass="mediumColumn columnCenter" />
<asp:BoundField DataField="TransactionGroupsEntry.branchNumber" HeaderText="Branch" ItemStyle-CssClass="mediumColumn columnCenter" />
<asp:BoundField DataField="TransactionGroupsEntry.cashInTicketAmount" HeaderText="Cash-In Ticket Amount" ItemStyle-CssClass="mediumColumn columnCenter" />
<asp:BoundField DataField="TransactionGroupsEntry.createdBy" HeaderText="Created By" ItemStyle-CssClass="mediumColumn columnCenter" />
<asp:BoundField DataField="TransactionGroupsEntry.dateCreated" HeaderText="Date Created" ItemStyle-CssClass="mediumColumn columnCenter" />
</Columns>
<EmptyDataTemplate>
<span style="font-weight: bold;">No Transactions have been entered</span>
</EmptyDataTemplate>
</asp:GridView>
Edit::
This is what I currently have following the advise of the first answer:

You would need to convert the first column into a template field. The template field's ItemTemplate would then contain a server side control (i.e LinkButton). This control could then have a server side OnClick event attached to it that would handle the server side logic. Below is an example:
<asp:TemplateField HeaderText="BatchID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="btnBatchId" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TransactionGroupsEntry.groupID") %>' OnClick="btnBatchId_Click" Text='<%# DataBinder.Eval(Container.DataItem, "TransactionGroupsEntry.groupID") %>' />
</ItemTemplate>
</asp:TemplateField>
In your code behind file your click event could look like the below example. I have added the ability to parse out/get at the id that is associated to the LinkButton:
protected void btnBatchId_Click(object sender, EventArgs e) {
var linkButton = sender as LinkButton;
if (linkButton != null) {
var batchId = 0;
if (int.TryParse(linkButton.CommandArgument, out batchId)) {
// batchId variable should contain a valid integer value
}
}
}

Related

How to find the HTML input button on gridview row data bound event without adding runat="Server" tag

I have following code in html
<asp:GridView ID="grdFiles" runat="server" AutoGenerateColumns="false" Width="100%" OnRowDataBound="grdFiles_RowDataBound" >
<Columns>
<asp:BoundField DataField="BatchNo" HeaderText="Batch No" />
<asp:BoundField DataField="totalspnumber" HeaderText="Total SP Number" />
<asp:BoundField DataField="VendorName" HeaderText="Vendor Name" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="prefix" HeaderText="Prefix" />
<asp:BoundField DataField="dateofexport" HeaderText="Date Of Export" />
<asp:BoundField DataField="ExpiryDate" HeaderText="Expiry Date" />
<asp:TemplateField>
<ItemTemplate>
<input id="downloadButton" fileid="<%# Eval("id") %>" filename="<%# Eval("exportedFileName") %>" type="button" tee="<%# Eval("isexported") %>" value="<%# Eval("isexported").ToString()=="2"?"Download again?":"Download" %>" onclick="SetFileUploaded(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am trying to find the downloadButton in gridview OnRowDataBound event but its shows null,
here is my c# code
protected void grdFiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataControlFieldCell cell = (DataControlFieldCell)e.Row.Controls[7];
// Access the button
HtmlInputButton downloadButton = (HtmlInputButton)cell.FindControl("downloadButton");
// Check the condition
if (true)
{
// Hide the button
downloadButton.Visible = false;
}
}
}
Why use a "input" html button?
why not just drop in a plain jane asp.net button, and use that?
And don't bother with the gridview event model, you don't care, and don't need it. (not worth the trouble).
So, say we have this grid:
<asp:GridView ID="GridFiles" runat="server"
AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" CssClass="table">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="UpLoadTime" HeaderText="UpLoaded" />
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="140px"
ImageUrl='<%# "UpLoadFiles/" + Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad"
runat="server" Text="Download" CssClass="btn"
OnClick="cmdDownLoad_Click"
CommandArgument='<%# Eval("FileName") %>' />
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load:
GridFiles.DataSource = MyRst("SELECT * FROM MyUpLoadFiles");
GridFiles.DataBind();
Ok, so when we click the download button in that gv?
Then this code:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button myBut = sender as Button;
GridViewRow gRow = myBut.NamingContainer as GridViewRow;
string strFileOnly = gRow.Cells[0].Text;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
}
So, you are "always" free to pick up/get/use/enjoy the current row click with above.
And note how I did use the cell's colleciton, but since I setup the command arugment of a plain jane button with this:
CommandArgument='<%# Eval("FileName") %>'
Then code behind becomes this:
Button myBut = sender as Button;
string strFileOnly = myBut.CommandArgument;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
So, just use a standard everyday button, and pick up the grid view row as per above. Or use a expression for the button command argument, and you may well not even have to mess with, or worry about the grid row, but use that simple button command argument.
So, above grid when displayed looks like this:

Showing and hiding of gridview button based on the value of a cell in the same row

I have a gridview in my ASP.NET. in my gridview columns, i want the button on each row to show or hide if the value of a cell is the same cell is empty or null. for example, i want a button to show on each row that has Signout_Time as null or empty. i have written the code below. the issue i'm having is that the codes works in an opposite way. Buttons are showed on the rows with "Signout_Time" while the button on rows without a value for "Signout_Time" visibility becomes false. it shouldn't be so. I have also tried changing my if conditions, it still didnt work
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
switch (e.Row.RowType) {
case DataControlRowType.DataRow:
DataRowView myDataRowView = (DataRowView)e.Row.DataItem;
if (String.IsNullOrEmpty(myDataRowView["Signout_Time"].ToString())) {
Button status = (Button)e.Row.FindControl("out");
if (status != null) {
status.Visible = true;
}
}
break
}
}
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action" Visible="True">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut" CommandArgument='<%#Eval("SN") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>
You can set the button Visibility directly in the GridView Template:
<asp:Button Visible='<%# string.IsNullOrEmpty(Eval("Signout_Time").ToString()) %>' runat="server" Text="Sign out" ID="out" CommandName="SignOut" CommandArgument='<%#Eval("SN") %>'/>

How do I get the value of a particular row in my Gridview

I have a Gridview which also contains a button field. When this button on a particular row is clicked, I want it to update my database. For example, if a row contains (SN = 1) I want it to update the button to update the database with the row that contains "SN = 1". How do I get the SN of the row when the button on that same row is clicked?
This is my Gridview definition:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>
Here, when the row button is clicked, I want to update my database with the signout time. I can't seem to get it to get the SN of the row and update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
}
}
If the value you seek is the comes from the same datasource, you can add the value as a CommandArgument:
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out"
runat="server"
Text="Sign out"
CommandName="SignOut"
CommandArgument='<%# Eval("SN") %>'/>
</ItemTemplate>
</asp:TemplateField>
On your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
string sn = e.CommandArgument.ToString();
if (sn == "1")
{
/*DO STUFF....*/
}
}
}

ASP.NET Gridview ItemTemplate Access in CodeBehind

I am having trouble accessing an asp.NET HiddenField from a Gridview ItemTemplate in the codebehind. I need to be able to read the values that these hiddenfields contain so that I can execute the delete method.
The code is as follows
<%# Control Language="C#" AutoEventWireup="true" CodeFile="MemberList.ascx.cs" Inherits="UserControls_MemberList" %>
<asp:RadioButtonList ID="ReportSelect" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">All</asp:ListItem>
<asp:ListItem Value="2">Current Members</asp:ListItem>
<asp:ListItem Value="3">Perspective Members</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="ReportSelectButton" runat="server" OnClick="ReportSelectButton_Click"
Text="Select Report Type" />
<asp:Button ID="LinkToHomePage" runat="server" Text="Back to Homepage" OnClick="LinkToHomePage_Click">
</asp:Button>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Height="308px"
Width="1282px" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField HeaderText="First Name" AccessibleHeaderText="FirstName" DataField="FirstName">
</asp:BoundField>
<asp:BoundField HeaderText="Last Name" AccessibleHeaderText="LastName" DataField="LastName">
</asp:BoundField>
<asp:BoundField HeaderText="Street Address" AccessibleHeaderText="StreetAddress"
DataField="StreetAddress"></asp:BoundField>
<asp:BoundField HeaderText="City" AccessibleHeaderText="City" DataField="City"></asp:BoundField>
<asp:BoundField HeaderText="State" AccessibleHeaderText="State" DataField="State">
</asp:BoundField>
<asp:BoundField HeaderText="Zip" AccessibleHeaderText="Zip" DataField="Zip"></asp:BoundField>
<asp:BoundField HeaderText="Birthday" AccessibleHeaderText="Birthday" DataField="Birthday" />
<asp:BoundField HeaderText="Email" AccessibleHeaderText="Email" DataField="Email">
</asp:BoundField>
<asp:BoundField HeaderText="PrimaryPhone" AccessibleHeaderText="PrimaryPhone" DataField="PrimaryPhone" />
<asp:BoundField HeaderText="AlternatePhone" AccessibleHeaderText="AlternatePhone"
DataField="AlternatePhone" />
<asp:BoundField HeaderText="Pending" AccessibleHeaderText="Pending" DataField="Pending" />
<asp:BoundField HeaderText="IsMember" AccessibleHeaderText="IsMember" DataField="IsMember" />
<asp:BoundField HeaderText="Username" AccessibleHeaderText="Username" DataField="Username">
</asp:BoundField>
<asp:BoundField HeaderText="Description" AccessibleHeaderText="Descripton" DataField="Description" />
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"/>
<asp:HiddenField ID="HiddenUsername" Value='<%#Bind("Username") %>' runat="server" />
<asp:HiddenField ID="HiddenEmail" Value='<%#Bind("Email") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind
protected void DeleteButton_Click(object sender, EventArgs e)
{
HiddenField Username = GridView1.FindControl("HidderUsername") as HiddenField;
HiddenField Email = GridView1.FindControl("HiddenEmail") as HiddenField;
string username = Username.Value;
string email = Email.Value;
AdminAccess.DeleteMemberApplication(username, email);
}
Any help would be greatly appreciated.
The HiddenField controls are going to be part of a <td> which is one of the <tr> the GridView renders. The GridView control's FindControl only knows of it's immediate children and as the Hidden controls are two levels below that, it's not going to find them. Instead, start from the sender and try to find its sibling Hidden controls. Replace the two HiddenControl lines in the event handler as below:
HiddenField Username = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenUsername");
HiddenField Email = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenEmail");
And it should get the values you are looking for to delete the data in that row.
Just use CommandArgument of button
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"
CommandArgument='<%#Eval("Username")+"^"+Eval("Email") %>'/>
</ItemTemplate>
</asp:TemplateField>
protected void DeleteButton_Click(object sender, EventArgs e)
{
var btn = sender as Button;
var args = btn.CommandArgument.Split('^');
string username = args[0];
string email = args[1];
AdminAccess.DeleteMemberApplication(username, email);
}

Checkbox in TemplateField in Gridview loses checked on postback

I have a gridview with a template field. In that template field is a checkbox. I have a submit button outside of the gridview to assign the records that were checked. On the postback no checkboxes register as being checked. Here is my Code:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cb" Checked="false" runat="server" />
<asp:Label ID="lblCFID" runat="server" Visible="false" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="Name" HeaderText="Name" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="DOB" HeaderText="Date of Birth" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Gender" DataField="Gender" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Status" DataField="Status" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Plan Name" DataField="PlanName" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Type" DataField="ControlType" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Date of Service" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" DataField="DateofService" />
</Columns>
protected void AssignRecords(object sender, EventArgs e)
{
int Rows = gvASH.Rows.Count;
for (int i = 0; i < Rows; i++)
{
//CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
CheckBox cb = (CheckBox)gvASH.Rows[i].Cells[0].FindControl("cb");
Label lblID = (Label)gvASH.Rows[i].Cells[0].FindControl("lblCFID");
if (cb.Checked == true)
{
string ID = lblID.Text;
//Assign Code
}
}
}
I have a breakpoint set on the string ID = lblID.Text; but it never finds any that are checked.
I think what you are missing is, when you click on the button and your page is postback, you rebinding to gridview, you need to bind in this condition like
if (!Page.IsPostBack)
{
GridView1.DataSourceID = "yourDatasourceID";
GridView1.DataBind();
}
On a postback, the contents of the GridView are re-created from the postback Viewstate data between page_init and page_load. Perhaps try examining your Gridview in page_load to see what's there.
set the autopostback attribute of Checkbox
AutoPostBack="true"

Categories

Resources