Button onclick in DetailsView - c#

How can I use button onclick in DetailsView? So far I have this.
<asp:DetailsView ID="DetailsView1"
DefaultMode= "Edit" AutoGenerateEditButton="False" AutoGenerateInsertButton="True"
AutoGenerateDeleteButton="True" DataSourceID="SqlDataSource2" runat="server"
AutoGenerateRows="False" DataKeyNames="fileID" >
<Fields>
<asp:BoundField DataField="fileID" HeaderText="fileID" InsertVisible="False" ReadOnly="True" SortExpression="fileID" />
<asp:BoundField DataField="filenameName" HeaderText="filenameName" SortExpression="filenameName" />
<asp:TemplateField HeaderText="filePath" SortExpression="filePath">
<EditItemTemplate>
<asp:FileUpload ID="FileEditUpload1" Width="300px" runat="server" /> <br />
<asp:Button ID="Button1" runat="server" Text="Upload file" onclick="Button1_Click"/>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("filePath") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("filePath") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Createdby" HeaderText="Createdby" SortExpression="Createdby" Visible="False" />
<asp:BoundField DataField="CreatedDt" HeaderText="CreatedDt" SortExpression="CreatedDt" Visible="False" />
<asp:BoundField DataField="Updatedby" HeaderText="Updatedby" SortExpression="Updatedby" Visible="False" />
<asp:BoundField DataField="UpdatedDt" HeaderText="UpdatedDt" SortExpression="UpdatedDt" Visible="False" />
<asp:BoundField DataField="Active" HeaderText="Active" SortExpression="Active" Visible="False" />
</Fields>
</asp:DetailsView>
code-behind
protected void Button1_Click(object sender, EventArgs e)
{
//Get path from web.config file to upload
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
bool blSucces = false;
string filename = string.Empty;
string pathname = string.Empty;
string filePathName = string.Empty;
if (FileEditUpload1.HasFile)
{
}

You can access the fileUpload control from the DetailsView like this:
protected void Button1_Click(object sender, EventArgs e)
{
//Get path from web.config file to upload
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
bool blSucces = false;
string filename = string.Empty;
string pathname = string.Empty;
string filePathName = string.Empty;
//To access the file upload control
//First get the clicked button
Button btn = (Button)sender;
//Then get the detailsview row
DetailsViewRow drv = (DetailsViewRow)btn.Parent.Parent;
//Now you can access the FileUpload control
FileUpload FileEditUpload1 = (FileUpload)drv.FindControl("FileEditUpload1");
if (FileEditUpload1.HasFile)
{
//Do the rest of your code
}
}
Give it a try and if you faced any problems please inform me.

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:

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

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;
}

Unable to get posted file name in GridView when uploading file

Unable to get posted file name in GridView when uploading file.
Here is what I tried with.
ASPX File content is shown below:
<asp:GridView ID="GVProtocol" runat="server" AllowPaging="True"
HorizontalAlign="Center" CssClass="DGList" HeaderStyle-CssClass="DGHeader"
RowStyle-CssClass="DGRow" AlternatingRowStyle-CssClass="DGRowAlt" OnRowCommand="GVProtocol_RowCommand"
OnPageIndexChanging="GVProtocol_PageIndexChanging" Height="90px" Width="100%" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="SL NO" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20">
<ItemTemplate>
<%# (( ( GridView ) ( ( GridViewRow ) Container ).Parent.Parent ).PageSize + Container.DataItemIndex + 1)- 15 %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="NAME" />
<asp:BoundField HeaderText="Unit" DataField="UNIT" />
<asp:BoundField HeaderText="Standard Value" DataField="STANDARD_VALUE" />
<asp:TemplateField HeaderText="Upload XML" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:FileUpload ID="FileUpload" runat="server" EnableViewState="true" />
<asp:Button runat="server" ID="btnUpload" Text="upload" CommandArgument="<%# Container.DataItemIndex %>" CommandName="upload" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FilePath" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="200">
<ItemTemplate>
<asp:Label runat="server" ID="lblFilePath">-</asp:Label>
<asp:LinkButton ID="btnDownload" runat="server" CommandName="download" CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pagerStyle" />
<HeaderStyle Wrap="False" CssClass="DGHeader" />
<RowStyle CssClass="DGRow" />
<AlternatingRowStyle CssClass="DGRowAlt" HorizontalAlign="Center" />
</asp:GridView>
This is the CodeBehind file for the above ASPX content:
protected void GVProtocol_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int Index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "upload")
{
string strFilePathTemp = Server.MapPath("~/ProtocolCommunication/");
//int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
LinkButton lbDownload = (LinkButton)GVProtocol.Rows[Index].FindControl("btnDownload");
lbDownload.Text = "<span class='glyphicon glyphicon-download-alt'>";
Label lblFilePathTemp = (Label)GVProtocol.Rows[Index].FindControl("lblFilePath");
lblFilePathTemp.Text = strFilePathTemp;
FileUpload fileUpload = (FileUpload)GVProtocol.Rows[Index].FindControl("FileUpload");
if(fileUpload != null)
{
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
fileUpload.PostedFile.SaveAs(strFilePathTemp + fileName);
}
}
if (e.CommandName == "download")
{
Label lblFilePathTemp = (Label)GVProtocol.Rows[Index].FindControl("lblFilePath");
string fileNameAndPath = lblFilePathTemp.Text.ToString();
string file = Path.GetFileName(fileNameAndPath);
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fileNameAndPath));
Response.TransmitFile(Server.MapPath("~/ProtocolCommunication/"));
Response.End();
}
}
catch(Exception ex)
{
throw ex;
}
}
Looking for possible solution for the above problem.
I got solution,,by using
asp:updatePanel control with postbacktrigger to hold the control ID's which are dynamically created in girdview. and using this you can upload and download files to any of the gridview row.

how to get the specific row value from corresponding button click in gridview [duplicate]

This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}

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);
}

Categories

Resources