Nested GridView - How to trigger the Child GridView Button Click event - c#

I need to show a Master/Child data in a page and I have used multiple GridViews to achieve the same. So, I have created two GridViews (Parent & Child) and now I want to fire the Button click event (i.e. btnLock) from the child gridview control and do some DB operations. So, I dont know how to achieve this.
Please help.
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>' onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("CustomerID")%>
:
<%#Eval("CompanyName")%>
(<%#Eval("TotalOrders")%>
Orders) </span>
</div>
<asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = #CustomerID)">
<SelectParameters>
<asp:Parameter Name="CustomerID" Type="String" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
<div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
<asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="110px" />
<asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnLock" Text="Lock" CommandName="Lock" CommandArgument=<%# Eval("OrderID") %> runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Thanks

Use the RowCommand:
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false"
onrowcommand="gvOrders_RowCommand"
>
........
</asp:GridView >
protected void gvOrders_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Lock")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
//dowork
}
}

Related

How to change the data in a asp gridlist on click with UserControls?

I'm trying to change the data of my gridlist on my homepage when you click on a button.. Tried many things nothing works. When I press the button to change gridview data nothing happpens and few secons later I get a error
How it looks: http://prntscr.com/7fa9qh
The Error : http://prntscr.com/7faam0
I have left some code out to make it not all to big, like I only have 2 buttons in code but there are more
list.aspx.cs :
protected void Page_Load(object sender, EventArgs e) {
GvTop2000 usercontrol = (GvTop2000)Page.LoadControl("~/Pages /Usercontrols/ListGv/GvTop2000.ascx");
pnlGVList.ContentTemplateContainer.Controls.Add(usercontrol);
}
protected void btnTop2000_Click(object sender, EventArgs e) {
pnlGVList.ContentTemplateContainer.Controls.Clear();
GvTop2000 usercontrol = (GvTop2000)Page.LoadControl("~/Pages/Usercontrols/ListGv/GvTop2000.ascx");
pnlGVList.ContentTemplateContainer.Controls.Add(usercontrol);
pnlGVList.Update();
}
protected void btnNieuw_Click(object sender, EventArgs e) {
pnlGVList.ContentTemplateContainer.Controls.Clear();
GvNieuw usercontrol = (GvNieuw)Page.LoadControl("~/Pages/Usercontrols/ListGv/GvNieuw.ascx");
pnlGVList.ContentTemplateContainer.Controls.Add(usercontrol);
pnlGVList.Update();
}
list.aspx :
<asp:Content ID="ContentHolderDD" runat="server" ContentPlaceHolderID="ContentHolderDD">
<asp:ScriptManagerProxy ID="smProxy" runat="server" />
<%-- Year selector --%>
<asp:DropDownList ID="ddlJaar" CssClass="ddl" runat="server" DataSourceID="DSYears" DataTextField="top2000jaar" DataValueField="top2000jaar" AutoPostBack="True" />
<asp:SqlDataSource runat="server" ID="DSYears" ConnectionString='<%$ ConnectionStrings:TOP2000_IAO4A_GROEP2ConnectionString %>' SelectCommand="sp_get_year" SelectCommandType="StoredProcedure" />
</asp:Content>
<asp:Content ID="ContentPlaceholderButtons" runat="server" ContentPlaceHolderID="ContentPlaceholderButtons">
gvTop2000 usercontrol:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="GvTop2000.ascx.cs" Inherits="Top2000.Pages.Usercontrols.ListGv.GvTop2000" %>
<asp:GridView runat="server" ID="gridList" CellPadding="10" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataSourceID="DSList" AllowPaging="True" PageSize="100" CssClass="GridListings">
<Columns>
<asp:BoundField DataField="positie" HeaderText="Positie" SortExpression="positie"></asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="artiestid" DataNavigateUrlFormatString="Artists.aspx?id={0}" DataTextField="naam" HeaderText="Artiest" />
<asp:HyperLinkField DataNavigateUrlFields="songid" DataNavigateUrlFormatString="Song.aspx?id={0}" DataTextField="titel" HeaderText="Titel" />
<asp:BoundField DataField="jaar" HeaderText="Jaar" SortExpression="jaar"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="DSList" ConnectionString='<%$ ConnectionStrings:TOP2000_IAO4A_GROEP2ConnectionString %>' SelectCommand="sp_top2000_year" SelectCommandType="StoredProcedure" >
<SelectParameters>
<asp:ControlParameter PropertyName="SelectedValue" DefaultValue="" Name="YEAR" Type="Int32" ControlID="ContentHolderDD$ddlJaar" />
</SelectParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="pnlCButtons">
<ContentTemplate>
<asp:Button ID="btnTop2000" runat="server" Text="Top2000" OnClick="btnTop2000_Click" />
<asp:Button ID="btnNieuw" runat="server" Text="Nieuw" OnClick="btnNieuw_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:Content id="ContentPlaceHolder1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<%-- GridView --%>
<asp:UpdatePanel ID="pnlGVList" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="phGv"/>
</ContentTemplate>
</asp:UpdatePanel>
gvNieuw usercontrol :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="GvNieuw.ascx.cs" Inherits="Top2000.Pages.Usercontrols.ListGv.GvNieuw" %>
<asp:GridView runat="server" ID="gridList" CellPadding="10" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataSourceID="sqlDS" AllowPaging="True" PageSize="100" CssClass="GridListings" DataKeyNames="songid,top2000jaar,songid1,artiestid1">
<Columns>
<asp:BoundField DataField="songid" HeaderText="songid" SortExpression="songid" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="top2000jaar" HeaderText="top2000jaar" SortExpression="top2000jaar" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="positie" HeaderText="positie" SortExpression="positie" />
<asp:BoundField DataField="songid1" HeaderText="songid1" InsertVisible="False" ReadOnly="True" SortExpression="songid1" />
<asp:BoundField DataField="artiestid" HeaderText="artiestid" SortExpression="artiestid" />
<asp:BoundField DataField="titel" HeaderText="titel" SortExpression="titel" />
<asp:BoundField DataField="jaar" HeaderText="jaar" SortExpression="jaar" />
<asp:BoundField DataField="artiestid1" HeaderText="artiestid1" InsertVisible="False" ReadOnly="True" SortExpression="artiestid1" />
<asp:BoundField DataField="naam" HeaderText="naam" SortExpression="naam" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS" runat="server" ConnectionString="<%$ ConnectionStrings:TOP2000_IAO4A_GROEP2ConnectionString %>" SelectCommand="sp_new_songs_year" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ContentHolderDD$ddlJaar" Name="top2000Year" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

How to disable LinkButton within GridViewclick from Client Side using JavaScript?

I have a GridView, In one column I have LinkButton control. I want to disable click from client side for certain condition on this column. Means for some rows it will not be possible for User to call onclick event and for some rows it is possible.
I want to achieve this from client side using javascript.
Or When User clicks on link, It will notify the User that this action can't be completed for this row.
<asp:GridView Width="100%" ShowHeader="true" ViewStateMode="Enabled" GridLines="Both" CellPadding="10" CellSpacing="5" ID="GridViewMultiplePOSAssociationId" runat="server" AllowSorting="false" AutoGenerateColumns="false" OnRowCommand="RewardGridMultiD_RowCommand"
AllowPaging="true" PageSize="8" OnRowDataBound="grdViewCustomers_OnRowDataBound" PagerSettings-Position="Top" PagerSettings-Mode="NumericFirstLast" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last" DataKeyNames="POS Id">
<RowStyle CssClass="table_inner_text" BackColor="WhiteSmoke" BorderColor="CornflowerBlue" Wrap="true" ForeColor="Black" Height="30px" />
<HeaderStyle CssClass="table_head_text" />
<Columns>
<asp:TemplateField ItemStyle-Width="80px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval(" POS Id ") %>');">
<img alt="Details" id="imgdiv<%# Eval("POS Id") %>" src="images/plus.png" />
</a>
<div id="div<%# Eval(" POS Id ") %>" style="display: none;">
<asp:GridView ID="grdViewOrdersOfCustomer" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<RowStyle CssClass="table_inner_text" BackColor="SkyBlue" BorderColor="Black" Wrap="true" ForeColor="White" Height="30px" />
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="RULE FILE NAME" HeaderText="RULE FILE NAME" />
<asp:BoundField ItemStyle-Width="150px" DataField="RULE ID" HeaderText="RULE ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="RULE TYPE ID" HeaderText="RULE TYPE ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="START TIME" HeaderText="START TIME" />
<asp:BoundField ItemStyle-Width="150px" DataField="EXPIRY TIME" HeaderText="EXPIRY TIME" />
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="Row Number">
<ItemTemplate>
<asp:Label ID="LabelRowNumberId" runat="server" Text='<%#Eval("Row Number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="POS Id">
<ItemTemplate>
<asp:Label ID="LabelPOSID" runat="server" Text='<%#Eval("POS Id") %>'></asp:Label>
<%-- <asp:LinkButton ID="LinkbtnPOSId" CommandArgument='<%#Eval("POS Id") %>' CommandName="ClickPOS" Text='<%#Eval("POS Id") %>' runat="server" CausesValidation="false"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="HyperLinkAssociate" CommandArgument='<%#Eval("POS Id") %>' CommandName="Associate" Text="Associate" runat="server" OnClientClick="return OnClientClickAssociateRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>/
<asp:LinkButton ID="HyperLinkReplace" CommandArgument='<%#Eval("POS Id") %>' CommandName="Replace" Text="Replace" runat="server" OnClientClick="return OnClientClickReplaceRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Status">
<ItemTemplate>
<asp:Label runat="server" ID="LabelStatusPendingPOSId" Text='<%#Eval("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In GridViewMultiplePOSAssociationId there is one column "Status" which has label LabelStatusPendingPOSId, LabelStatusPendingPOSId text is set Applied, Not Applied at the time of Binding. For Rows which has Status Applied, User should not be able to click on LinkButton Associate/Replace else He is allowed to click.
use this code OnRowDataBound for Your Grid
protected void grdViewCustomers_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType==DataControlRowType.DataRow)
{
LinkButton LinkbtnPOSId=(LinkButton)e.Row.FindControl("LinkbtnPOSId");
Label LabelStatusPendingPOSId = (Label)e.Row.FindControl("LabelStatusPendingPOSId");
Boolean boolStatus = LabelStatusPendingPOSId.Text == "Applied" ? true : false;
//LinkbtnPOSId.Attributes.Add("onclick", "function CheckStatus('" + boolStatus.ToString() + "')");
LinkbtnPOSId.Enabled = boolStatus;
}
}
Try this..
You can loop through the Gridview and make the particular control disable...
I am writing the code in javascript pageload function...
function PageLoad(sender, args)
{
for (var i = 0; i <= RowCount; i++)
{
document.getElementById('Gridview1_HyperLinkAssociate_' + i.toString() + '').disabled = true;
}
}
Set RowCount as the number of rows of the Gridview...

Add check box to gridview

I've a grid view with three columns Employee name Employee details and Employee age.
I want to add a check box at each row and after selection of each check box i want to fire a insert query associated to that employee.
Can you tell me how to add this dynamic functionality to the grid view.
also if we use <%# EVAL %> i don't know how to implement it with checkbox.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="details" HeaderText="details"
SortExpression="details" />
<asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connApps %>"
SelectCommand="SELECT [name], [details], [age] FROM [tblA]">
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Selected item name:<br>";
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
if (chk.Checked)
{
Label1.Text += item.Cells[1].Text + "<br>";
}
}
}
}
Output:
Here is an example ,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
For more information , check Here !
you can use TemplateFields for the GridView:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind use below code:
ClusterName = GV.Rows(1).Cells(2).FindControl("myLabelinTheGridViewTemplateField")

Gridview not updating value

I am trying to make my gridview update a SQL record but it is not updating the values.
Here is the aspx code:
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
onrowcancelingedit="GridView1_RowCancelling"
OnRowDeleting ="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
DataKeyNames="RID"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:TemplateField Visible="false" HeaderText="RID">
<ItemTemplate>
<asp:Label runat="server" ID="RID" Text='<%#Bind("RID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Short Description">
<ItemTemplate>
<asp:Label runat="server" ID="short_lbl" Text='<%#Bind("SHORT_DESCRIPTION") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="SHORT_DESCRIPTION" Text='<%#Bind("SHORT_DESCRIPTION") %>' />
<asp:RequiredFieldValidator runat="server" ID="valShort" ControlToValidate="SHORT_DESCRIPTION" ValidationGroup="var1" ErrorMessage="*" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label runat="server" ID="desc_label" Text='<%#Bind("DESCRIPTION") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="DESCRIPTION" Text='<%#Bind("DESCRIPTION") %>' />
<asp:RequiredFieldValidator runat="server" ID="valLast" ControlToValidate="DESCRIPTION" ValidationGroup="var1" ErrorMessage="*" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the update function itself.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label RID = GridView1.Rows[e.RowIndex].FindControl("RID") as Label;
TextBox SHORT_DESCRIPTION = GridView1.Rows[e.RowIndex].FindControl("SHORT_DESCRIPTION") as TextBox;
TextBox DESCRIPTION = GridView1.Rows[e.RowIndex].FindControl("DESCRIPTION") as TextBox;
String UpdateQuery = string.Format("UPDATE TAXONOMIES SET SHORT_DESCRIPTION='{0}', DESCRIPTION='{1}' WHERE RID = {2}", SHORT_DESCRIPTION.Text, DESCRIPTION.Text, Convert.ToInt32(RID.Text));
GridView1.EditIndex = -1;
BindGridData(UpdateQuery);
}
If I put a breakpoint and look at the value, I can see that is is not the newly typed in value. I'm not sure what is going on.
I think the problem is you are binding you grid on the page-load event.
try binding it in if (!IsPostBack)
Example
private void Page_Load()
{
if (!IsPostBack)
{
//bind your grid here.
}
}
use this code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="regGroupID" HeaderText="regGroupID"
SortExpression="regGroupID" />
<asp:BoundField DataField="amountReceived" HeaderText="amountReceived"
SortExpression="amountReceived" />
<asp:BoundField DataField="other" HeaderText="other" SortExpression="other" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Table]"
UpdateCommand="UPDATE [Table] SET [regGroupID] = #regGroupID, [amountReceived] = #amountReceived, [other] = #other WHERE [id] = #id">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="regGroupID" Type="Int32" />
<asp:Parameter Name="amountReceived" Type="Decimal" />
<asp:Parameter Name="other" Type="String" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
here I set id as the primary key
table structure is
Try changing the Eval to Bind. Eval is read-only so you can't actually update the 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