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.
Related
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;
}
}
}
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;
}
}
}
}
I have a gridview that works fine with SQLDataSource. Edit, Delete buttons works perfectly.
However, when I search any record and try to edit that record, the gridview opens up the first row in the edit mode.
I don't know what i have done wrong.
Here is my code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Customer_id"
DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display." AllowPaging="True"
AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="Horizontal"
PageSize="5" Width="873px" onrowediting="GridView1_RowEditing" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" ></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Select" Text="Select"></asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Customer_id" HeaderText="Customer_id" ReadOnly="True"
SortExpression="Customer_id" InsertVisible="False" />
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:BoundField DataField="Customer_Type" HeaderText="Customer_Type" SortExpression="Customer_Type" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"
Font-Bold="True" Font-Italic="True" Font-Overline="True" Font-Size="Large" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
And the Code Behind looks like this:
protected void Page_Load(object sender, EventArgs e)
{
string vs = (string)ViewState["buttonClicked"];
string isEditing = (string)ViewState["isEditing"];
if (IsPostBack)
{
if (vs == "False")
{
RadioButtonListChanged();
GridView1.DataBind();
}
else if (vs == "True")
{
btnSearch_Click(sender, e);
GridView1.DataBind();
}
}
}
protected void RadioButton1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonListChanged();
}
private void RadioButtonListChanged()
{
ViewState["buttonClicked"] = "False";
string sqlString;
if (RadioButton1.SelectedItem.Text != "All")
{
sqlString = "Select * from customers where status='True' and customer_type = '" + RadioButton1.SelectedValue.ToString() + "' order by customer_name";
}
else
{
sqlString = "Select * from customers where status='True' order by customer_name";
}
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
ViewState["buttonClicked"] = "True";
string sqlString;
sqlString = "Select * from customers where status='True' and customer_name like '%" + txtCustomerName.Text + "%' order by customer_type, customer_name";
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.DataBind();
}
You are binding the grid again in each post back, so the current row index is set to zero every time and this causes the first row to be edited.
Change you code to:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!IsPostBack)
...
}
You need to modify your code a little bit from:
protected void Page_Load(object sender, EventArgs e)
{
string vs = (string)ViewState["buttonClicked"];
string isEditing = (string)ViewState["isEditing"];
if (IsPostBack)
{
if (vs == "False")
{
RadioButtonListChanged();
GridView1.DataBind();
}
else if (vs == "True")
{
btnSearch_Click(sender, e);
GridView1.DataBind();
}
}
}
To:
protected void Page_Load(object sender, EventArgs e)
{
string vs = (string)ViewState["buttonClicked"];
string isEditing = (string)ViewState["isEditing"];
if (**!IsPostBack**)
**^^^**
/*just bind gridview when page is not
postback this will not bind oyur gridview on your every request*/
if (vs == "False")
{
RadioButtonListChanged();
GridView1.DataBind();
}
else if (vs == "True")
{
btnSearch_Click(sender, e);
GridView1.DataBind();
}
}
}
I found the solution here
Gridview Selects Wrong Row For Editing
in page_load event
if (IsPostBack)
{
SqlDataSource1.SelectCommand = (string)Session["sqlString"];
SqlDataSource1.DataBind();
}
and when i am searching i did this in button event
Session["sqlString"] = sqlString;
That wasn't simple :)
I have a grid view as under
<asp:GridView ID="dgTask" runat="server" Width="100%"
AutoGenerateColumns="False" onrowdatabound="dgTask_RowDataBound">
<Columns>
<asp:BoundField DataField="TaskID" HeaderText="TaskID" ItemStyle-Width="1%" />
<asp:BoundField DataField="TaskName" HeaderText="Task Name" ItemStyle-HorizontalAlign="left"
ItemStyle-Width="10%" />
<asp:BoundField DataField="PriorityName" HeaderText="Priority" ItemStyle-HorizontalAlign="center"
ItemStyle-Width="10%" />
<asp:BoundField DataField="StatusName" HeaderText="Status" ItemStyle-HorizontalAlign="center"
ItemStyle-Width="10%" />
<asp:TemplateField HeaderText="Edit Task" ItemStyle-Width="10%">
<ItemTemplate>
<asp:LinkButton ID="lnkBtnEdit" runat="Server" Text="Edit" CommandArgument ='<%# Eval("TaskID") %>' />
<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now, what I have to do is that on click event of the linkButton, i need to hide the text box controls for that row.
How to do so?
So far I have done as under
protected void dgTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton btnEdit = (LinkButton)e.Row.Cells[4].FindControl("lnkBtnEdit");
btnEdit.Attributes.Add("onclick", "return Test();");
}
}
Thanks
You are on the right track, just make minor changes in calling the javascript function and also add the javascript function as below.
protected void dgTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton btnEdit = (LinkButton)e.Row.Cells[4].FindControl("lnkBtnEdit");
TextBox txtId = (TextBox)e.Row.Cells[4].FindControl("txtId");
btnEdit.Attributes.Add("onclick", "return Test("'" + txtId.ClientId + "'");");
}
}
And add Javascript like this way,
function Test(var txtId)
{
var inputtxt = document.getElementById(txtId);
if(inputtxt != null)
{
inputtxt.Attributes.Add("style","display:none;");
}
}
Try This :
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
GridViewRow r = (GridViewRow)b.NamingContainer;
((TextBox)(GridView1.Rows[r.RowIndex].Cells[0].FindControl("TextBox1"))).Visible = false;
}
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