Gridview in asp.net VS2008
I have a gridview control and I want to display checkboxes for each row. Checkboxes should only appear if Session ["DisplayBox"] == true.
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" EnableSortingAndPagingCallbacks="True"
AllowPaging="True" DataSourceID="JObjectDataSource" PageSize="5" OnRowCommand="gridView_RowCommand"
DataKeyNames="ID" Width="100%">
<Columns>
<asp:TemplateField HeaderText="Review">
<ItemTemplate>
<asp:CheckBox ID="chkRejectFile" AutoPostBack="true" runat="server" OnCheckedChanged="chkRejectFile_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
I removed some of the columns and kept the one I'm asking about. How to place conditional code in aspx page and check session value?
Also, if I am pages, I need to explicitly handle the tracking, which row was checked and which was not?
source to share
Add a new event property to the grid like this:
OnRowDataBound="gridView_RowDataBound"
Then, in code, add the following appropriate event handler:
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// check for null first
object displayBoxFlag = Session["DisplayBox"];
if(displayBoxFlag!=null && (bool) displayBoxFlag)
{
e.Row.FindControl("chkRejectFile").Visible = true;
}
else
{
e.Row.FindControl("chkRejectFile").Visible = false;
}
}
}
Lots of room for optimization, but it should work.
What happens is that ASP.NET will raise this event and call a method for each row of the grid immediately after they are bound. Now you can go and override or customize the way it is displayed.
source to share
You want to set the Visible property based on the value of the session variable. Add the following code to your control (untested):
Visible='<%# Convert.ToBoolean(HttpContext.Current.Session["DisplayBox"]) %>'
Note that this does not check if the session variable is actually defined, i.e. depends on its installation and is installed either in true
or false
.
If you are paging and care about maintaining the checked status, you will need to track the checked state for each item explicitly. The only things that will be submitted for submission are the controls that are actually on the page at the time of submission.
source to share