Hide a LinkButton inside an UpdatePanel, which is inside a GridView - c#

Is it possible to hide a LinkButton inside an UpdatePanel, which is inside a GridView? or am I going about this the complete wrong way?
I want to disable the lnkDownload button when ExpenseReceipt is null in the database and display the text "No Receipt".
when I debug, lnkDownload comes back as null.
ASP.NET:
<asp:GridView ID="gvTillExpenseRegistration" runat="server" AutoGenerateColumns="False"
EmptyDataText="No expense registered today." GridLines="Horizontal" SkinID="SimpleBlackWhite"
CellPadding="10" Caption="Today's Expense Registration" OnRowCommand="gvTillExpenseRegistration_RowCommand" DataKeyNames="ExpenseID, FileName">
<Columns>
<asp:BoundField DataField="ExpenseID" HeaderText="ExpenseID" Visible="False"/>
<asp:BoundField DataField="Description" HeaderText="Type" />
<asp:BoundField DataField="TotalAmount" HeaderText="Amount" SortExpression="TotalAmount"
DataFormatString="{0:0.00}">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="RegisterDate" HeaderText="Time" DataFormatString="{0:hh:mm tt}">
</asp:BoundField>
<asp:BoundField DataField="RegisteredBy" HeaderText="User"></asp:BoundField>
<asp:BoundField DataField="FileName" HeaderText="FileName" Visible="False"/>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="updDownload" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandName="Download" Text='Download' />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#:
private void LoadTodaysExpensesByTill(int tillID)
{
DataTable dt = new DataTable();
dt = new TillEndOfDayDAL().GetTodaysExpensesByTillID(tillID);
pnlTillExpenseRegistration.Visible = false;
if (dt != null && dt.Rows.Count > 0)
{
gvTillExpenseRegistration.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
if (row["ExpenseReceipt"] == DBNull.Value)
{
LinkButton lnkDownload = (LinkButton)gvTillExpenseRegistration.FindControl("lnkDownload");
lnkDownload.Enabled = false;
lnkDownload.Text = "No Receipt";
}
}
pnlTillExpenseRegistration.Visible = true;
}
gvTillExpenseRegistration.DataBind();
}

You can set the Text and Enabled properties of the LinkButton inline with a ternary operator.
<asp:LinkButton ID="lnkDownload" runat="server"
Text='<%# string.IsNullOrEmpty(Eval("ExpenseReceipt").ToString()) ? "No Receipt" : "Download" %>'
Enabled='<%# string.IsNullOrEmpty(Eval("ExpenseReceipt").ToString()) ? false : true %>' />
And it would be better to wrap the GridView in the UpdatePanel, not UpdatePanel inside ItemTemplates. This could give unexpected behavior.
However in your case you could remove it completely since you are adding an UpdatePanel, and then set a PostBackTrigger, making the panel useless anyway.

You need to change your code as per below
aspx
<asp:GridView ID="gvTillExpenseRegistration" runat="server" AutoGenerateColumns="False"
EmptyDataText="No expense registered today." GridLines="Horizontal" SkinID="SimpleBlackWhite"
CellPadding="10" Caption="Today's Expense Registration" OnRowCommand="gvTillExpenseRegistration_RowCommand" OnRowDataBound="GrdView_RowDataBound" DataKeyNames="ExpenseID, FileName">
<Columns>
<asp:BoundField DataField="ExpenseID" HeaderText="ExpenseID" Visible="False" />
<asp:BoundField DataField="Description" HeaderText="Type" />
<asp:BoundField DataField="TotalAmount" HeaderText="Amount" SortExpression="TotalAmount"
DataFormatString="{0:0.00}">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="RegisterDate" HeaderText="Time" DataFormatString="{0:hh:mm tt}"></asp:BoundField>
<asp:BoundField DataField="RegisteredBy" HeaderText="User"></asp:BoundField>
<asp:BoundField DataField="FileName" HeaderText="FileName" Visible="False" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField runat="server" ID="hdnExpenseReceipt" Value='<%# Eval("ExpenseReceipt") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="updDownload" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandName="Download" Text='Download' />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
private void LoadTodaysExpensesByTill(int tillID)
{
DataTable dt = new DataTable();
dt = new TillEndOfDayDAL().GetTodaysExpensesByTillID(tillID);
pnlTillExpenseRegistration.Visible = false;
if (dt != null && dt.Rows.Count > 0)
{
gvTillExpenseRegistration.DataSource = dt;
pnlTillExpenseRegistration.Visible = true;
}
gvTillExpenseRegistration.DataBind();
}
and also created one method
protected void GrdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
HiddenField hdnExpenseReceipt = (HiddenField)e.Row.FindControl("hdnExpenseReceipt");
if (string.IsNullOrWhiteSpace(hdnExpenseReceipt.Value))
{
LinkButton lnkDownload = (LinkButton)gvTillExpenseRegistration.FindControl("lnkDownload");
lnkDownload.Visible = false;
}
}
This method will call each time when row created in gridview.
try and let me know.

Try adding an event on gvTillExpenseRegistration
<asp:GridView ID="gvTillExpenseRegistration" runat="server"
OnRowDataBound="gvTillExpenseRegistration_DataBound"
..
protected void gvTillExpenseRegistration_DataBound(object sender, EventArgs e)
{
}

Related

Update row for specific column on Webform App

I have a table which contains recipe for each item. Actually I wanted to update my specific column in the table. This table contains Item ID,Stock Code,Stock Name,Stock Group Name,Stock Unit Name,Amount Needed indexes. First of all ı could update and it is working, but when I want to update only my Amount column but when I press edit button, the TextBox opens for each columns. I want only amount row for the TextBox open.
This is the code:
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal" OnRowDeleting="grdItems_RowDeleting" OnRowEditing="grdItems_RowEdit" meta:resourcekey="GridView5Resource1" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete" BackColor="DarkRed" style="color: White" />
<%-- <asp:Button ID="btnUpdate" runat="server" CausesValidation="false" CommandName="Update" Text="Update" BackColor="Green" style="color: White" />
--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" BackColor="Green" style="color: White" />
<asp:Button Text="Cancel" runat="server" OnClick="OnCancel" BackColor="DarkRed" style="color: White"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="_IdItemHam" HeaderText="Item ID" SortExpression="_IdItemHam" meta:resourcekey="BoundFieldResource9" />
<asp:BoundField DataField="item_code" HeaderText="Item Code" SortExpression="item_code" meta:resourcekey="BoundFieldResource1" />
<asp:BoundField DataField="item_name" HeaderText="Item Name" SortExpression="item_name" meta:resourcekey="BoundFieldResource2" />
<asp:BoundField DataField="item_group_name" HeaderText="Item Group Name" SortExpression="item_group_name" meta:resourcekey="BoundFieldResource3" />
<asp:BoundField DataField="item_unit_name" HeaderText="Item Unit" SortExpression="item_unit_name" meta:resourcekey="BoundFieldResource4" />
<asp:BoundField DataField="_Amount" HeaderText="Amount Needed" SortExpression="_Amount" ReadOnly="false" meta:resourcekey="BoundFieldResource6" />
<%--<asp:BoundField DataField="PROC" HeaderText="PROC" SortExpression="PROC" meta:resourcekey="BoundFieldResource8" />--%>
</Columns>
<SelectedRowStyle BackColor="#CCCCFF" />
</asp:GridView>
And here is my .cs code:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
string amount = (row.Cells[6].Controls[0] as TextBox).Text;
//DataTable dt = ViewState["dt"] as DataTable;
//dt.Rows[row.RowIndex]["Amount Needed"] = amount;
//ViewState["dt"] = dt;
((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials.ElementAt(grdItems.EditIndex)._Amount = Double.Parse(amount);
grdItems.EditIndex = -1;
grdItems.DataSource = ((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials;
grdItems.DataBind();
CalculateProductCost();
}
Can you please help me about how to make that event. Thanks from now!
I would suggest you use the event OnRowUpdating, implemented in the GridView.
After that you can get the values and keys in the event, do your save statement and bind the grid.
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal"
OnRowUpdating="grdItems_RowUpdating">
.cs code:
protected void grdItems_RowUpdating(object sender, GridViewUpdateEventArgs e){
object id = e.Keys["_IdItemHam"];
int amount = Convert.ToInt32(e.NewValues["_Amount"]);
//Do your update statment
//After that bind the grid
grdItems.DataBind();
}
use GridView_RowCommand to implement edit action
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow row;
GridView grid = sender as GridView;
switch (e.CommandName)
{
case "Edit":
index = Convert.ToInt32(e.CommandArgument);
row = grid.Rows[index];
//use row to find the selected controls you need for edit, update, delete here
break;
}
}

Edit gridview row asp.net without using commandfield

I would like to make a column editable in a gridview but without the edit column (the one with the keys update, cancel ...) due to space problems. I tried to recall the javascript functions related to those buttons in the onRowDataBound but onclick event is not taken. Here my code. Can anyone help me please?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex == GridView1.EditIndex) //GridView is in edit mode
{
//update or cancel buttons
LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
string updateScript = ClientScript.GetPostBackClientHyperlink(updateBtn, "");
Button1.Attributes["onclick"] = updateScript;
string cancelScript = string.Format("javascript:__doPostBack('{0}','Cancel${1}')", GridView1.ID, e.Row.RowIndex);
Button2.Attributes["onclick"] = cancelScript;
}
else //GridView is in read mode
{
//edit button
string editScript = string.Format("javascript:__doPostBack('{0}','Edit${1}')", GridView1.ID, e.Row.RowIndex);
e.Row.Attributes["onclick"] = editScript;
}
}
if (GridView1.EditIndex >= 0)
{
Button1.Enabled = true;
Button2.Enabled = true;
}
else
{
Button1.Enabled = false;
Button2.Enabled = false;
}
}
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" DataKeyNames="PKCOD" AllowPaging="True" PageSize="10"
CssClass="auto-style1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<%--
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<br />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" EnableClientScript="False" ErrorMessage="ErrorMessage" MaximumValue="999" MinimumValue="0" Type="Integer">Valori tra 0 e 999</asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
--%>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<ItemTemplate>
<asp:TextBox ID="textBoxQuantita" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" Type="Double" MinimumValue="0" MaximumValue="999" ControlToValidate="textBoxQuantita" runat="server"
ErrorMessage="Inserisci solo numeri compresi tra 0 e 999"></asp:RangeValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CODICE" HeaderText="CODICE" ReadOnly="True" SortExpression="CODICE" />
<asp:BoundField DataField="DESCRIZIONE" HeaderText="DESCRIZIONE" ReadOnly="True" SortExpression="DESCRIZIONE" />
<asp:BoundField DataField="CATEGORIA" HeaderText="CATEGORIA" ReadOnly="True" SortExpression="CATEGORIA" Visible="False" />
<asp:BoundField DataField="PKCOD" HeaderText="PKCOD" ReadOnly="True" SortExpression="PKCOD" InsertVisible="False" Visible="False" />
<asp:BoundField DataField="USERNAME" HeaderText="USERNAME" ReadOnly="True" SortExpression="USERNAME" Visible="False" />
<asp:BoundField DataField="USERID" HeaderText="USERID" ReadOnly="True" SortExpression="USERID" Visible="False" />
<asp:BoundField DataField="USERDT" HeaderText="USERDT" ReadOnly="True" SortExpression="USERDT" Visible="False" />
<asp:BoundField DataField="STATO" HeaderText="STATO" ReadOnly="True" SortExpression="STATO" Visible="False" />
</Columns>
</asp:GridView>

CheckBox gets checked in the second click in c# GridView

Background: The problem I have with my code is the following. Upon the first click of a button the checkbox doesn't get the checked checkboxes, but on the second click just get all the checked checkboxes.
Here is the code:
ASPX
This button execute the process..
<asp:LinkButton ID="lbDeletePerman" runat="server" OnClick="lbDeletePerman_Click">Yes</asp:LinkButton>
<code><asp:UpdatePanel ID="GVUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView CssClass="da-table" ID="Gv_A" runat="server" DataKeyNames="ID,PatientName" AutoGenerateColumns="false" OnRowCommand="Gv_Appoint_RowCommand">
<Columns>
<asp:TemplateField HeaderStyle-Font-Bold="true" HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CbE" runat="server" />
<asp:HiddenField ID="hID" Value='<%# Eval("IDENTIFICATION") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=""Date" HeaderText="Date" HeaderStyle-Font-Bold="true" HeaderStyle-VerticalAlign="Middle" ItemStyle-VerticalAlign="Middle" />
<asp:BoundField DataField="Cat" HeaderText="Type" HeaderStyle-Font-Bold="true" HeaderStyle-VerticalAlign="Middle" ItemStyle-VerticalAlign="Middle" />
<asp:BoundField DataField="Deleted" HeaderText="Deleted" HeaderStyle-Font-Bold="true" HeaderStyle-VerticalAlign="Middle" ItemStyle-VerticalAlign="Middle" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
C#:
protected void lbDeletePerman_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow rowItem in Gv_Appoint.Rows)
{
CheckBox CboxElim = (CheckBox)(rowItem.Cells[0].FindControl("CbE"));
if (CboxElim.Checked)
{
LBLT.Text = "Hello"; // NO ENTERING HERE
}
}
GVUpdatePanel.Update();
} catch (Exception er){}
}
Any help would be appreciated
lbDeletePerman needs to be inside UpdatePanel together with Gv_A.
Or use the AsyncPostBackTrigger
<asp:LinkButton ID="lbDeletePerman" runat="server"
OnClick="lbDeletePerman_Click">Yes</asp:LinkButton>
<asp:UpdatePanel ID="GVUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lbDeletePerman" />
</Triggers>
<asp:GridView>...</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>

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")

Categories

Resources