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?

0


source to share


4 answers


Add a callback handler for the OnDataBind event for the GridView. Then, on each line, define whether or not to show the checkbox.



The code will of course be in your .cs file.

+2


source


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.

+1


source


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.

0


source


You can override the OnRowDataBound event in the code behind and for each row do your logic and set the visisble property accordingly.

0


source







All Articles