disable a checkbox in gridview - c#

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

Related

asp.net Gridview RowDataBound disables grid paging

I have a GridView that I populate from my SQL. The grid has a page size of 7. I'm making use of the RowDataBound event to replace "<" and ">" characters with "`" which works as expected.
However, the problem is that it disables Paging on the grid. When the grid has more than 7 items, paging should be enabled so that I can go to Page 2, but the paging doesn't work as soon as I use the RowDataBound event.
My code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
GrdOpsBook.DataSource = OperationalEmployees.getEmpbookedBySpecificDate(DateTime.Today);
GrdOpsBook.DataBind();
if (GrdOpsBook.Rows.Count == 0)
lblNoOpsBooking.Visible = true;
lblWelcome.Text = "Welcome " + Session["UserLoggedInName"] + " to the Energy Insight Booking Application";
}
else
Response.Redirect("LogIn.aspx");
}
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Text = cell.Text.Replace(">", "`");
cell.Text = cell.Text.Replace("<", "`");
}
}
My GridView
<asp:GridView ID="GrdOpsBook" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
CellPadding="4" AllowPaging="True" EnableSortingAndPagingCallbacks="True"
PageSize="7"
ForeColor="Black" GridLines="Vertical" Width="100%" AutoGenerateColumns="False" >
<AlternatingRowStyle BackColor="LightGray" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
<Columns>
<asp:BoundField DataField="Operator" HeaderText="Operator" ItemStyle-Width="10%" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Destination" HeaderText="Destination" ItemStyle-Width="58%" HtmlEncode="false" ItemStyle-Wrap="true"/>
<asp:BoundField DataField="Start Time" HeaderText="Start Time" ItemStyle-Width="6%" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:hh\:mm}" />
<asp:BoundField DataField="End Time" HeaderText="End Time" ItemStyle-Width="6%" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:hh\:mm}" />
<asp:BoundField DataField="Booked By" HeaderText="Booked By" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Number of Days Booked" HeaderText="Number of Days Booked" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
over here you iterate over each row
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Text = cell.Text.Replace(">", "");
cell.Text = cell.Text.Replace("<", "");
}
}
you should restrict your iteration to DataRows
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit)
Thank you, I did it this way and it works well without disabling the paging
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Replace the "<" tag with "`".
string sDestination = e.Row.Cells[1].Text.Replace("<", "`");
e.Row.Cells[1].Text = sDestination;
}
}

Dynamic link in asp.net gridview

I'm trying to create a gridview with an extra column that contains a hyperlink for each row. Unfortunately my hyperlinks doesn't start from the top of the column, instead they are started from the second row of the hyperlink's column.
See this picture for more information >>> http://i.imgur.com/TLsVo5s.png
As you can see in that picture, there is a 'view' column that contains hyperlinks, but the problem is the first row is always empty. The hyperlink that's on the second row should be on the first, and the third should be on the second, and so on.
Can anyone show me where I went wrong?
Here is my gridview declaration on my aspx page:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting" PageSize="20" DataKeyNames="no_kwitansi"
DataSourceID="home1" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" RowStyle-Wrap="False" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<RowStyle HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
<Columns>
<asp:BoundField HeaderText="#" />
<asp:BoundField DataField="no_kwitansi" HeaderText="No.Kwitansi" SortExpression="no_kwitansi" ReadOnly="True" />
<asp:BoundField DataField="nama_vendor" HeaderText="Vendor" SortExpression="nama_vendor" />
<asp:BoundField DataField="nama_pekerja" HeaderText="Pekerja" SortExpression="nama_pekerja" />
<asp:BoundField DataField="nama_penanggungjawab" HeaderText="Penanggungjawab" SortExpression="nama_penanggungjawab" />
<asp:BoundField DataField="satuan" HeaderText="Satuan" SortExpression="satuan" />
<asp:BoundField DataField="jumlah" HeaderText="Nominal" SortExpression="jumlah" />
<asp:BoundField DataField="tanggal" HeaderText="Tanggal" SortExpression="tanggal" />
</Columns>
</asp:GridView>
Here is my C# code behind:
This is my page_load function, I created the template field here.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["SortExpr"] = Sort_Direction;
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
home1.DataBind();
}
}
Here is my gridview rowDataBound function, where I create the hyperlink.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
hlContro.NavigateUrl = "./Home.aspx?ID=" + GridView1.Rows[i].Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
}
e.Row.Cells[8].Controls.Add(hlContro);
}
}
so why not just a template field, and remove all the server side boilerplate? What happen if you would change position of your column?
Below is the solution where you need not to write anything in your server side code. Simple and easy.
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("no_kwitansi") %>'
NavigateUrl= '<%# "./Home.aspx?ID=" + Eval("no_kwitansi") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.
Just write code like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
hlContro.NavigateUrl = "./Home.aspx?ID=" + e.Row.Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
e.Row.Cells[8].Controls.Add(hlContro);
}
}
why are you adding it from code behind even you can add in html page
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="test1" runat="server" ForeColor="#525252" Text="Documents" />
</ItemTemplate>
</asp:TemplateField>
a similar example is shown on this link you can try Link

get the ID of any Item in NavigateUrl in GridView

Hello i have this gridview:
<asp:GridView ID="grd1" width="100%" AutoGenerateColumns="False" runat="server" EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:HyperLinkField DataTextField="Plan Reference" HeaderText="Plan Reference" SortExpression="Plan Reference" NavigateUrl="https://www.yahoo.com?itemid="/>
</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" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center"/>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
When I indicate on the plan reference column , then the url appears in the bottom left corner of the window like this: https://www.yahoo.com?itemid=
I want the id of the row that I indicate on it , appear in the url in the bottom left corner of the window, how can I code it?
This is my CS code :
DataTable GetData()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWeb = oSiteCollection.OpenWeb();
SPList oSpList = oWeb.Lists["Drill Plans"];
SPListItemCollection oSpListItemCollection = oSpList.Items;
DataTable dt = new DataTable();
try
{
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Plan Reference", typeof(String));
DataRow dataRow;
foreach (SPListItem oSplistItem in oSpListItemCollection)
{
//DateTime date = DateTime.Now;
//string currentDate = String.Format("{0:dddd, MMMM dd, yyyy}", date);
dataRow = dt.Rows.Add();
dataRow["ID"] = oSplistItem["ID"].ToString();
dataRow["Plan Reference"] = oSplistItem["Plan Reference"].ToString();
}
return dt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
return dt;
}
}
Please help me.
I need a help for important work please
To append the ID of the bound item to the url you can use Container.DataItem like this:
<asp:HyperLinkField
DataTextField="Plan Reference"
HeaderText="Plan Reference"
SortExpression="Plan Reference"
NavigateUrl='https://www.yahoo.com?itemid=<%# Container.DataItem("ID") %>'/>
More info here.
EDIT
In order for the above to work, you need to bind your GridView to the data table returned from method GetData(). In your Page_Load method you should have something like this:
if(!IsPostback)
{
grd1.DataSource = GetData();
grd1.DataBind();
}
Another approach would be to handle the RowDataBound event of your GridView and set the NavigateUrl in there. To do so, you'll need to assign an id to the HyperLinkField (let's call it "link"). Here is the code:
protected void OnGridViewRowDataBound(object sender, GridViewRowEventArgs e)
{
var hyperLink = e.Row.FindControl("link") as HyperLinkField;
if(hyperLink != null)
{
var row = e.Row.DataItem as DataRow;
hyperlink.NavigateUrl = String.Format("https://www.yahoo.com?itemid={0}", row["ID"]);
}
}
Of course, don't forget to add the event handler in your markup:
<asp:GridView ID="grd1" RowDataBound="OnGridViewRowDataBound" ..
</asp:GridView>

Gridview linkbutton postbackurl change on page load event

I have a gridview with a linkbutton, the url linkbutton is assigned using a code by replacing a key word with a name from the DB.
all works fine, except that when I click the back button in browser and try different link I get this error:
"The HTTP verb POST used to access path '/System.Web.UI.WebControls.Label' is not allowed"
below is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var HyperLink = row.FindControl("LinkButton1") as LinkButton;
var RepID = row.FindControl("Label1") as Label;
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", RepID.Text + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="report_id" DataSourceID="SqlDataSource1" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("report_name")%>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("report_subject")%>'></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
I think the problem might be that you're doing your binding at the Page_Load stage of the page life cycle. Try moving your foreach code to a
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var HyperLink = e.Row.FindControl("LinkButton1") as LinkButton;
//var RepID = row.FindControl("Label1") as Label;
//You should be able to access your field without referencing the label too
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var myField = row.Field<string>("report_name");
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", myField + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}

Filtered Gridview does edit correct row

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

Categories

Resources