I have a GridView in an update panel.
The GridView is styled so that each alternate row is a different colour.
When I change page on the GridView it loses the alternate row colouring. All other styles are maintained.
If I remove the update panel the GridView keeps the alternate row colouring after changing page.
Does anyone have any idea on what may be causing this or how to fix it?
Thanks,
Neil
EDIT:
Here is the aspx code
<div id="active-logbooks" class="tab-content clearfix">
<div class="left-column">
<asp:MultiView runat="server" ID="mlvLogbooks" >
<asp:View runat="server" ID="vActiveLogbooks">
<asp:GridView PagerSettings-Mode="NextPrevious" PagerSettings-Position="Top" PagerSettings-NextPageImageUrl="~/img/right-arrow.png" PagerSettings-PreviousPageImageUrl="~/img/left-arrow.png" AllowPaging="true" runat="server" ID="gvActiveLogbooks" PageSize="5" AutoGenerateColumns="false" CssClass="lesson stripe-me" OnRowDataBound="gvActiveLogbooks_RowDataBound" OnPageIndexChanging="gvActiveLogbooks_PageIndexChanging">
<Columns>
<asp:BoundField HeaderText="Logbook number" DataField="LogbookNumber" ItemStyle-CssClass="border" ItemStyle-Width="100" />
<asp:BoundField HeaderText="Origin" DataField="Origin" ItemStyle-CssClass="border" ItemStyle-Width="100" />
<asp:BoundField HeaderText="Order Reference" DataField="OrderReference" ItemStyle-CssClass="border" ItemStyle-Width="100" />
<asp:TemplateField HeaderText="Transfer Date">
<ItemTemplate>
<asp:Literal runat="server" ID="lblTransferDate" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="lnkTransferLogbook" CssClass="border" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Previous<asp:Literal runat="server" ID="litBreaker" Text=" |" />
Next
</asp:View>
</asp:MultiView>
</div>
And this is the function that is called when the page change occurs:
protected void gvActiveLogbooks_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
HideShowGridViewPagerLinks(e.NewPageIndex);
gvActiveLogbooks.DataSource = _logbooks;
gvActiveLogbooks.PageIndex = e.NewPageIndex;
gvActiveLogbooks.DataBind();
}
Nowhere on the page is there anything done with colouring the GridView rows
protected void gvActiveLogbooks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
Literal transferLabel = (Literal)e.Row.Cells[(int)ActiveLogbookGridViewColumns.TransferDate].FindControl("lblTransferDate");
transferLabel.Text = _logbooks[e.Row.RowIndex].TransferDate.ToShortDateString();
HyperLink transferLink = (HyperLink)e.Row.Cells[(int)ActiveLogbookGridViewColumns.TransferLink].FindControl("lnkTransferLogbook");
transferLink.Text = TransferLinkText;
transferLink.NavigateUrl = "TransferLogbooks.aspx?id=" + Guid.NewGuid();
}
I'm guessing that some interaction between your CSS classes and the postback is messing this up. What happens if you switch to the RowStyle and AlternateRowStyle tags (example here), and reference your CSS classes using the CssClass property on those tags?
Related
I have grid view
one column is ItemTemplate column which has Checkbox field.
Other 2 columns are Databound columns. One column is ButtonField which is of Button type.
I want this button to initially set to disabled mode
Once the Checkbox is checked it should be enabling that particular row button field. Could anyone help in this?
My sample try
.aspx file
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Button" />
</Columns>
</asp:GridView>
.aspx.cs file
protected void CheckBox2_CheckedChanged1(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gridrow = ((GridViewRow)(chk.Parent));
if (chk.Checked)
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = true;
}
else
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = false;
}
}
Try using the below code:
ASPX code for the GridView1:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind (for CheckBox Check Changed Event handler):
protected void CheckBox2_CheckedChanged1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView3.Rows)
{
((Button)row.FindControl("Button1")).Enabled = ((CheckBox)row.FindControl("non_prod_all_select")).Checked;
}
}
Changes made:
1.Set AutoPostBack for CheckBox to true.
2.Removed Button Field and added a template field with button in the third column of the Grid (so that the asp:Button control could be read easily in code behind)
3.Changed the code behind code to do the necessary.
NOTE: I have checked this code locally and is working as expected. So just replace your old code with this and let me know in case of any issues.
i have a checkbox in a template field of a gridview and i want to get the id of the record at a checkbox tick. how do i do it? i am doing asp.net and also by using datakeynames instead, my gridview also shows the datakeynames persID column. why?
my code:
<asp:GridView ID="GridViewHostelMember" runat="server" DataKeyNames="_PersID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="_PersID" HeaderText="_PersID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="DOB" HeaderText="DOB" />
<asp:BoundField DataField="FatherName" HeaderText="FatherName" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in this.GridViewHostelMember.Rows)
{
CheckBox chbTemp = item.FindControl("CheckBoxSelect") as CheckBox;
if (chbTemp != null)
{
if (chbTemp.Checked)
{
Label1.Text = item.Cells[0].Text;
}
}
}
}
_PersID is showing because autogeneratecolumns is set to true; if true, it shows all columns. To hide, set to false, and explicitly add the columns to the grid.
For the first part, at checkbox tick, you would need to set AutoPostBack="true" on the checkbox, which posts back, and then you can check the data key for the current row of the grid.
Reference -
my gridview also shows the datakeynames persID column. why?
true to automatically create bound fields for each field in the data
source; otherwise, false. The default is true.
It should be like below..
<asp:GridView ID="GridViewHostelMember" autogeneratecolumns="False"
runat="server" DataKeyNames="_PersID">
i want to get the id of the record at a checkbox tick. how do i do it?
Sample Code
protected void CheckBox_Checked(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//c.ValidationGroup is your ID
}
Sample HTML
<asp:GridView ID="ed" runat="server" OnRowCommand="GridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" ValidationGroup='<%#Eval("ID") %>' OnCheckedChanged="CheckBox_Checked" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >
i have two gridviews 1) master and 2) detail in my master gridview with few columns in it and a hyperlink so when the user click on the hyperlink (master gridview) i want the row to be highlight but below codes does not hold the highlighted row after it does the postback, how do i make sure that its highlight even after it does postback?
protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#C2D69B'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
e.Row.Attributes.Add("style", "cursor:pointer;");
//e.Row.Attributes.Add("onclick", "location='patron_detail.aspx?id=" + e.Row.Cells[0].Text + "'");
}
}
<asp:GridView runat="server" ID="gvReport" AutoGenerateColumns="False" CssClass="gv"
DataSourceID="LDS_POReport" Width="880px" AllowPaging="true" AllowSorting="true"
OnRowCreated="gvReport_RowCreated" OnRowDataBound="gvReport_RowDataBound" DataKeyNames="Id" PageSize="15">
<PagerStyle HorizontalAlign="Left" CssClass='header' BackColor="#E5EAF3" ForeColor="Black" />
<PagerSettings Mode="NumericFirstLast" />
<EmptyDataTemplate>
No Items</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Number Of Items" SortExpression="NumberOfItems">
<ItemTemplate>
<a href='Officer.aspx?Id=<%# Eval("Id") %>'>
<%# Eval("NumberOfItem")%>
</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
sorry for question... are you sure that you check between 2 integer values?... and if yes...
in the html that you have, do you have the background color in the TD elements of the table? If you have the color code in the html code, maybe it's a problem of css style definition.
Just put a row index in the query string and read it after the postback, then select the row based on index and change the color.
I would like the rows of my GridView to have strikethrough based on a bound data value called IsObsolete. I tried to do this:
<RowStyle BackColor="#EFF3FB" Font-Strikeout='<%# Bind('IsObsolete') %>' />
But obviously this doesn't parse. I'd rather not do this in GridView.DataBound(). Any other ideas?
I do this by applying a style on the DataBinding event of one of my controls in a template. Example:
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="SomeTitle">
<ItemTemplate>
<asp:HyperLink ID="hrefYourLink" runat="server"
NavigateUrl="Somepage.aspx?id={0}"
OnDataBinding="hrefYourLink_DataBinding"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then implement the OnDataBinding event:
protected void hrefYourLink_DataBinding(object sender, System.EventArgs e)
{
HyperLink link = (HyperLink)(sender);
GridViewRow row = (GridViewRow)(link.Parent.Parent);
if ((bool)(Eval("IsObsolete"))
{
row.CssClass = "StrikeThroughStyle";
}
link.Text = HttpUtility.HtmlEncode(((int)(Eval("ID"))).ToString());
link.NavigateUrl = string.Format(link.NavigateUrl, Eval("ID").ToString());
}
This is just an quick example with a column with a link that gets modified based on the databinding as well but you should be able to get the gist of if an tweak it to suit your needs. I like doing it on the databinding because I do no binding inline in my aspx code.
Since the RowStyle element is applicable to the entire grid, the only way to accomplish what you want would be to have TemplateItems set for all columns and apply a CssClass to each column based on that same data value.
I'm not sure for your reasoning for avoiding the DataBound event for doing this as that would be the simplest way to accomplish it.
You might also try using a formatting function and itemstyles. Stealing a tidbit of code from above and changing it:
<%
public string GetObsoleteClass(string obsolete)
{
bool obs = Convert.ToBoolean(obsolete);
obs ? return "myObsoleteClass" : return "myNotObsoleteClass";
}
%>
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="SomeTitle">
<ItemTemplate>
<asp:HyperLink ID="hrefYourLink" runat="server"
NavigateUrl="Somepage.aspx?id={0}"
OnDataBinding="hrefYourLink_DataBinding"></asp:HyperLink>
</ItemTemplate>
<itemstyle CssClass='<%# Eval("isObsolete") %>'>
</itemstyle>
</asp:TemplateField>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
<itemstyle CssClass='<%# Eval("isObsolete") %>'>
</itemstyle>
</asp:boundfield>
</Columns>
</asp:GridView>