Enable Linkbutton in Gridview when ASP.NET Button Clicked - c#

I have a gridview that displays a record with some linkbuttons.
What I want is when my ASP.NET ButtonStart is clicked enable the LinkButton in the Gridview
<asp:GridView ID="gvData" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="688px" AllowPaging="True" AllowSorting="True"AutoGenerateColumns="False"
OnRowCommand="gvData_RowCommand"
OnRowDataBound="gvData_RowDataBound">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" SortExpression="Id">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Received" HeaderText="Received" SortExpression="Received"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbClose" runat="server" CausesValidation="False" CommandName="CloseClicked"
OnClick="CloseClick_Click">Close</asp:LinkButton>
</ItemTemplate>
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:button runat="server" text="Start" ID="btnStart" />
I know how to disable it in RowDataBound.
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbClose = (LinkButton)e.Row.Cells[5].FindControl("lbClose");
if (lbClose == null)
{
return;
}
var lblReceive = (Label)e.Row.FindControl("lblReceive ");
if (lblReceive .Text == "" && !IsPostBack)
{
lbClose.Enabled = true;
lbEdit.Enabled = true;
lbDelete.Enabled = true;
}
}
}
I believe you have to call RowDataBound from the BtnStart Click event but am not sure.
protected void btnStartTrans_Click(object sender, EventArgs e)
{
//Enable lblClose in gridview
}

Just loop through the rows in the grid view and enable the lbClose in each row, like this:
protected void btnStartTrans_Click(object sender, EventArgs e)
{
// Loop through all rows in the grid
foreach (GridViewRow row in grid.Rows)
{
// Only look for `lbClose` in data rows, ignore header and footer rows, etc.
if (row.RowType == DataControlRowType.DataRow)
{
// Find the `lbClose` LinkButton control in the row
LinkButton theLinkButton = (LinkButton)row.FindControl("lbClose");
// Make sure control is not null
if(theLinkButton != null)
{
// Enable the link button
theLinkButton.Enabled = true;
}
}
}
}

Related

How to have select option only for 1st row in asp.net gridview?

I am having asp.net gridview wherein I am showing several record with select option.
But as per my requirement I only want 1st row on grid to have select option.
below is my aspx page code:
<asp:GridView ID="id" runat="server" AutoGenerateColumns="False" CellPadding="3"
ShowHeaderWhenEmpty="true" AutoGenerateSelectButton="True" PageSize="5" CssClass="mGridSmall"
GridLines="None" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="id_PageIndexChanging" OnRowDataBound="id_RowDataBound"
OnSelectedIndexChanged="id_SelectedIndexChanged">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="Col1" Visible="false" />
<asp:BoundField DataField="Col2" HeaderText="Col2" SortExpression="Col2"
Visible="true" />
<asp:BoundField DataField="Col3" HeaderText="Col3" SortExpression="Col3"
Visible="true" />
<asp:BoundField DataField="Col4" HeaderText="Col4" SortExpression="Col4"></asp:BoundField>
<asp:BoundField DataField="Col5" HeaderText="Col5" SortExpression="Col5"></asp:BoundField>
<asp:BoundField DataField="Col6" HeaderText="Col6" SortExpression="Col6"></asp:BoundField>
<asp:BoundField DataField="Col7" Visible="false"></asp:BoundField>
</Columns>
<PagerStyle CssClass="pgr" />
<SelectedRowStyle BackColor="#fcb814" />
</asp:GridView>
and here is my .cs file code for row binding:
protected void id_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
//sorting
e.Row.Cells[1].Text = Convert.ToString(drv.Row["Col1"]);
e.Row.Cells[2].Text = Convert.ToString(drv.Row["Col2"]);
//e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
e.Row.Cells[4].Text = Convert.ToString(drv.Row["Col4"]);
e.Row.Cells[5].Text = Convert.ToString(drv.Row["Col5"]);
e.Row.Cells[6].Text = Convert.ToString(drv.Row["Col6"]);
e.Row.Cells[7].Text = Convert.ToString(drv.Row["Col7"]);
}
}
catch (Exception ex)
{
clsErrorHandler.LogError(ex);
}
}
You can do this in the RowDataBound event. Check the Row Index and hide the Control in all the Cells but the first.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItemIndex > 0)
{
LinkButton lb = e.Row.Cells[0].Controls[0] as LinkButton;
lb.Visible = false;
}
}
}

Deleting Row from Gridview with SelectedIndexChanged

I have a gridview which has SelectedIndexChanged event implemented. Now, I added a template field with a LinkButton to delete the row. But, I'm not able to click the link button on GridView as it always fires SelectedIndexChanged.
How can I make Delete button work when SelectedIndexChanged functionality implemented.
<asp:GridView ID="gvOnboardingMembers" runat="server" AllowPaging="True" PageSize="30" AllowSorting="True" OnPageIndexChanging="gvOnboardingMembers_PageIndexChanging" OnRowDataBound="gvOnboardingMembers_RowDataBound" OnRowDeleting="gvOnboardingMembers_RowDeleting"
AutoGenerateColumns="False" OnSorting="gvOnboardingMembers_Sorting" EnableViewState="False" BackColor="White" BorderColor="#cccccc" BorderWidth="1px" CellPadding="2"
EmptyDataText="No onboarding member found" GridLines="None" OnSelectedIndexChanged="gvOnboardingMembers_SelectedIndexChanged" Width="100%">
<AlternatingRowStyle BackColor="#ededed" />
<Columns>
<asp:TemplateField HeaderText="OnboardingMemberID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblOnboardingMemberID" runat="server" Text='<%#Eval("OnboardingMemberID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="VendorName" HeaderText="Vendor" SortExpression="VendorName" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="BusinessFunctionDisplayName" HeaderText="Business Function" SortExpression="BusinessFunctionDisplayName" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="CreatedDate" HeaderText="Upload Timestamp" SortExpression="CreatedDate" HeaderStyle-HorizontalAlign="Left"/>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkRemoveEntry" runat="server" OnClick="lnkRemoveEntry_Click" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ItemStyle-Width="20" ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#cccccc" ForeColor="Black" />
<HeaderStyle BackColor="#6699cc" Font-Bold="True" ForeColor="White" BorderColor="#cccccc" BorderWidth="1px" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#fefefe" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
Backend code
protected void gvOnboardingMembers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvOnboardingMembers, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
DataRowView dataItem = (DataRowView)e.Row.DataItem;
var removeEntry = e.Row.FindControl("lnkRemoveEntry") as LinkButton;
removeEntry.CommandArgument = dataItem["OnboardingMemberID"].ToString();
}
}
protected void gvOnboardingMembers_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvOnboardingMembers.Rows)
{
if (row.RowIndex == gvOnboardingMembers.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
row.ToolTip = string.Empty;
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
row.ToolTip = "Click to select this row.";
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
BindOnboardingMember();
}
private void BindOnboardingMember()
{
DataView dv = new DataView(DataManager.ToDataTable<OnboardingMember>(DraftMembers));
dv.Sort = OnboardingMemberSortExpression;
gvOnboardingMembers.DataSource = dv;
gvOnboardingMembers.DataBind();
}
protected void lnkRemoveEntry_Click(object sender, EventArgs e)
{
var lnkButton = (LinkButton)sender;
}
protected void gvOnboardingMembers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if(DeleteOnboardingMember(Guid.Parse(((Label)(gvOnboardingMembers.Rows[e.RowIndex].Cells[0].FindControl("lblOnboardingMemberID"))).Text)))
BindOnboardingMember();
}
On please let me know, if there is anyway to prevent PostBack on selectedIndexChanged. I guess my delete events are not executing because my gridview is rebound every time page is posted back (see pageload event). But, this is required in order to make SelectedIndexChanged work properly.
I couldn't prevent this scenario but I implemented a work around using WebMethods on Delete click instead of regular RowDeleting event.
protected void gvOnboardingMembers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvOnboardingMembers, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
DataRowView dataItem = (DataRowView)e.Row.DataItem;
if ((e.Row.RowState & DataControlRowState.Edit) == 0)
{
LinkButton deleteButton = (LinkButton)e.Row.Cells[7].Controls[0];
if (deleteButton != null)
deleteButton.Attributes.Add("onclick", "return deleteOnboardingMember('" + dataItem["OnboardingMemberID"].ToString() + "');");
}
}
}
[WebMethod(EnableSession=true)]
public static void DeleteOnboardingMember(string onboardingMemberID)
{
if(new processingClass().DeleteOnboardingMember(Guid.Parse(onboardingMemberID)))
HttpContext.Current.Session["DraftMembers"] = null;
}
Script
<script type="text/javascript">
function deleteOnboardingMember(id) {
if (confirm("Are you sure you want to remove this entry?"))
{
$.ajax({
type: "POST",
url: "/OnboardingRequest.aspx/DeleteOnboardingMember",
async: false,
contentType: "application/json; charset=utf-8",
data: "{ 'onboardingMemberID': '" + id + "'}",
dataType: "json",
success: function () {
window.location.reload();
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.error + ")");
alert(err.Message);
},
failure: function () {
alert('failure');
}
});
}
return false;
}
</script>
Try this way.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindOnboardingMember();
}
}
Given your Gridview definition (I've excluded cosmetic stuff):
<asp:GridView ID="gvOnboardingMembers" runat="server"
AllowPaging="True"
PageSize="30"
AllowSorting="True"
OnPageIndexChanging="gvOnboardingMembers_PageIndexChanging"
OnRowDataBound="gvOnboardingMembers_RowDataBound"
OnRowDeleting="gvOnboardingMembers_RowDeleting"
OnSorting="gvOnboardingMembers_Sorting"
EnableViewState="False"
EmptyDataText="No onboarding member found"
OnSelectedIndexChanged="gvOnboardingMembers_SelectedIndexChanged">
You have a basic misunderstanding on how events are fired in a Gridivew. You cannot simply add a LinkButton called "Delete" and provide an event hander like this:
<asp:LinkButton ID="lnkRemoveEntry" runat="server"
OnClick="lnkRemoveEntry_Click"
Text="Delete" />
and expect to fire a GridView RowDeleting event. You need to provide a CommandName in the Button. For a Delete operation you need to add CommandName="Delete" to the Link Button. See this for more on handling GridView operations
A GridView recognizes several other CommandName values as well: "Insert", "Edit", "Update", "Cancel". Each fires it's own appropriate Gridview row specific events and the ALL fire the RowCommand event.
When you don't specify a DataSource you have to manually wire up all the editing command events, this includes making sure you grab the correct PK's to handle Delete and Update operations.

HyperLink to specific item in gridview row

So I am working on a basketball website. There is a gridview full of teams and what I would like is when you click on a team name, it links you to a new page that has info about the team. What I tried so far only links every team to the same details page.
Here is my gridview code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Team"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"
Height="340px" Width="776px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Rank" DataNavigateUrlFormatString="~/MemberPages/Details.aspx?Rank={0}"
HeaderText="Team" SortExpression="Team" ItemStyle-Width = "150" >
<ItemStyle Width="150px"></ItemStyle>
</asp:HyperLinkField>
<asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" />
<asp:BoundField DataField="PointsPerGame" HeaderText="PointsPerGame"
SortExpression="PointsPerGame" />
<asp:BoundField DataField="OpponentPointsPerGame"
HeaderText="OpponentPointsPerGame" SortExpression="OpponentPointsPerGame" />
<asp:BoundField DataField="TopPlayer" HeaderText="TopPlayer"
SortExpression="TopPlayer" />
</Columns>
</asp:GridView>
And here is what I tried in the cs file to databind them to a specific link:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Team"),new DataColumn("Ranking"), new DataColumn("PointsPerGame"),
new DataColumn("OpponentPointsPerGame"), new DataColumn("TopPlayer")});
GridView1.DataBind();
}
}
For that kind of show/hide logic on specific row, you will need to use GridView.RowDataBound event.
Use a TemplateField instead of BoundField.
Place HyperLink control inside.
Then retrieve the HyperLink control inside RowDataBound event.
Example Code
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="MyHyperLink" Text="My Text" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(
Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var myHyperLink = e.Row.FindControl("MyHyperLink") as HyperLink;
if(SOME_LOGIC)
{
myHyperLink.Visible = false;
}
}
}

Check/Uncheck not working in the paging handled in gridview

I have used the paging in the gridview.
I need the code for check/uncheck in gridview either in server side or client side.
I have tried without paging, it's working. I need it with paging.
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHGrid" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkGrid" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This technique is called maintaining the state of GridView CheckBox in Paging. One method to achieve this is as follows.
Create a Genric List of int or string to store the DataKeys related to Checked rows in it.
At PageIndexChanging before you set the PageIndex to new index. For each rows in GridView,
If checkbox is checked, store the id to the generic list.
If checkbox is unchecked & the ID exist in generic list, remove it from the list.
At RowDataBound event, for each DataRow, check if the DataKeyName is present in the Generic List. If so, find the CheckBox and make it checked.
A simple example with Products Table, Northwind Database is given below
The Markup
<asp:GridView ID="gvProducts" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
OnPageIndexChanging="gvProducts_PageIndexChanging"
OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsProducts" runat="server"
ConnectionString='<%$ ConnectionStrings:NorthwindConnectionString %>'
SelectCommand="SELECT * FROM Products">
</asp:SqlDataSource>
The Code Behind
private List<int> ProductIDs
{
get
{
if (this.ViewState["ProductIDs"] == null)
{
this.ViewState["ProductIDs"] = new List<int>();
}
return this.ViewState["ProductIDs"] as List<int>;
}
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow gvr in gvProducts.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
if (chkSelect.Checked && !this.ProductIDs.Contains(productID))
{
this.ProductIDs.Add(productID);
}
else if (!chkSelect.Checked && this.ProductIDs.Contains(productID))
{
this.ProductIDs.Remove(productID);
}
}
}
}
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvr = e.Row;
if (gvr.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
chkSelect.Checked = this.ProductIDs.Contains(productID);
}
}
}

disable a checkbox in gridview

I have a gridview in which the first column in a checkbox. The grid displays one or more records that are returned from the database upon user search (the grid is populated in a proc called "protected void DisplayGridData()"). If the "inactive" column of that record is "1", I would like to have the checkbox disabled. How can I accomplish that?
The html code is:
<asp:GridView ID="gvCanadaOrders" runat="server" AutoGenerateColumns="False" CellPadding="2" CellSpacing="2" GridLines="None" Width="100%" AllowPaging="True" PageSize="30"
onpageindexchanging="gvCanadaOrders_PageIndexChanging" ForeColor="#333333" DataKeyNames="RecID">
<Columns>
<asp:TemplateField HeaderText="Disable" >
<ItemTemplate>
<asp:CheckBox ID="cbPONumber" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Rec_ID" HeaderText="Rec_ID" HtmlEncode="False"></asp:BoundField>--%>
<asp:BoundField DataField="Inactive" HeaderText="Inactive" HtmlEncode="False" ></asp:BoundField>
<asp:BoundField DataField="PO_Number" HeaderText="PO Number" HtmlEncode="False" ></asp:BoundField>
<asp:BoundField DataField="VENDOR_NAME" HeaderText="Vendor Name"></asp:BoundField>
<asp:BoundField DataField="ITEM_DESC" HeaderText="Item Description"></asp:BoundField>
<asp:BoundField DataField="MFG_PART_NO" HeaderText="MFG Part Number"></asp:BoundField>
<asp:BoundField DataField="System_DATE" HeaderText="System Date"></asp:BoundField>
<asp:BoundField DataField="PRINT_DATE" HeaderText="Print Date"></asp:BoundField>
</Columns>
<FooterStyle CssClass="GridFooter" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle CssClass="GridPager" ForeColor="#333333" BackColor="#FFCC66" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle CssClass="GridHeader" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle CssClass="GridItem" BackColor="#FFFBD6" ForeColor="#333333" />
<AlternatingRowStyle CssClass="GridAltItem" BackColor="White" />
</asp:GridView>
The code that loads the gridview is:
protected void btnDisable_Click(object sender, EventArgs e)
{
try
{
string strPONumber = "";
foreach (GridViewRow gvr in gvCanadaOrders.Rows)
{
if (((CheckBox)gvr.FindControl("cbPONumber")).Checked == true)
{
string strRec_ID = gvCanadaOrders.DataKeys[gvr.RowIndex].Value.ToString();
//Update table here, diable inactive field;
SqlConnection con = new SqlConnection(strConn);
string sqlCanadaOrdersUpdate = "usp_CanadaOrders_Close";
SqlCommand cmdCanadaOrdersUpdate = new SqlCommand(sqlCanadaOrdersUpdate, con);
cmdCanadaOrdersUpdate.CommandType = CommandType.StoredProcedure;
cmdCanadaOrdersUpdate.Parameters.Add(new SqlParameter("#rec_ID", SqlDbType.VarChar, 50));
cmdCanadaOrdersUpdate.Parameters["#rec_ID"].Value = strRec_ID;
cmdCanadaOrdersUpdate.Parameters.Add(new SqlParameter("#usr_id", SqlDbType.VarChar, 50));
cmdCanadaOrdersUpdate.Parameters["#usr_id"].Value = User.Identity.Name.Substring(User.Identity.Name.Length - 7);
con.Open();
SqlDataAdapter sqladaCanadaOrdersUpdate = new SqlDataAdapter(cmdCanadaOrdersUpdate);
cmdCanadaOrdersUpdate.ExecuteNonQuery();
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Purchase Order " + strPONumber + " has been disabled.');", true);
}
}
The code for gridview databoundrow is:
void gvCanadaOrders_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}
Hook in to the RowDataBound event of the GridView. From there, you can cast the DataItem to your record type. A test for the flag then lets you modify the row controls.
I have this code in VB.net and did a quick conversion per your C# tag, so please forgive any errors.
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
MyObject myObj = (myObj)e.Row.DataItem;
if (myObj.flag) {
CheckBox cb = (CheckBox)e.Row.FindControl("myCheckBox");
cb.Enabled=false;
}
}
}
EDIT: Per your edit to the question, you do not have OnRowDataBound in your markup. You would need to add OnRowDataBound="gvCanadaOrders_RowDataBound". It works the same way you've gon OnPageIndexChanging.
Handle the RowDataBound event and use e.Row parameter to find your checkbox.
It won't work on all cases, if you are using the HTML checkbox you should proceed by other by disabling property from CSS:
e.Row.Cells[0].Attributes["disabled"] = "disabled";
Reference link

Categories

Resources