Solved

Gridview: invalid cast error on databound checkbox template field when column hidden

Posted on 2007-11-20
5
1,748 Views
Last Modified: 2013-11-26
In my Gridview, I have a column "Dinner"

        <asp:GridView ID="gvGuests" runat="server" AutoGenerateColumns="False"
            DataKeyNames="IX_Guest" DataSourceID="dsGuests" OnRowCancelingEdit="gvGuests_RowCancelingEdit" OnRowEditing="gvGuests_RowEditing" OnRowUpdated="gvGuests_RowUpdated" OnPreRender="gvGuests_PreRender">
            <Columns>
.
.
                <asp:TemplateField HeaderText="Dinner" SortExpression="Dinner" >
                    <EditItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("Dinner") %>' />
                    </EditItemTemplate>


which is hidden under a condition in the gridview's preRender handler:


        if ((int)dr.ItemArray[cols.IndexOf("DayCount")] == 1)
        {
            gvGuests.Columns[6].Visible = false;
        }
        else
        {
            gvGuests.Columns[6].Visible = true;
        }


When the user clicks the "edit" button for the row, I get an invalid cast exception on the template field line above.  The culprit is Checked='<%# Bind("Dinner") %>'.

Is there a way to keep a hidden template field from databinding, or is there a cast I should put on the expression?

Thanks


0
Comment
Question by:Zernk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 7

Expert Comment

by:nisarkhan
ID: 20320698
>> <asp:TemplateField HeaderText="Dinner" SortExpression="Dinner" >

in your code-behind you can make CheckBox1.Visible = false with whatever the condition....

or you can also you use below:

<asp:TemplateField HeaderText="Dinner" SortExpression="Dinner" Visible="false" >

hth
0
 

Author Comment

by:Zernk
ID: 20321563
I wasn't confident that setting the check box visibility instead of the column visibility would work, but I gave it a try anyway

CheckBox cb = (CheckBox)gvGuests.FindControl("Checkbox1");

returns null

Any idea on how to access Checkbox1?

As the asp code, I need to set the visibility in the code-behind, not in the aspx module.  The explicit value doesn't help my problem.

0
 
LVL 7

Accepted Solution

by:
nisarkhan earned 500 total points
ID: 20327760
protected void editGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  CheckBox chkCheckbox1= e.Row.FindControl("Checkbox1") as CheckBox ;

  if (chkCheckbox1 !=null)
  {
    //todo
  }
}
0
 

Author Comment

by:Zernk
ID: 20328477
Thanks.  That worked out.  IMO, it's a workaround for a bug in .net.  I think databinding should not occur if a container field or column is not visible.

Here's my code with the problem solved:  
<asp:TemplateField HeaderText="Dinner" SortExpression="Dinner" >
    <EditItemTemplate>
        <asp:CheckBox ID="cbDinner" runat="server" Checked='<%# Bind("Dinner") %>' />
    </EditItemTemplate>
 
 
 
    protected void gvGuests_PreRender(object sender, EventArgs e)
    {
        DataSourceSelectArguments args = new DataSourceSelectArguments();
        DataView dv = (DataView)dsSelectedSession.Select(args);
        DataTable dt = dv.ToTable();
        DataRow dr = dt.Rows[0];
        DataColumnCollection cols = dt.Columns;
        //show dinner for two-day sessions only
        if ((int)dr.ItemArray[cols.IndexOf("DayCount")] == 1)
        {
            gvGuests.Columns[6].Visible = false;
            Session["DayCount"] = 1;
 
        }
        else
        {
            gvGuests.Columns[6].Visible = true;
            Session["DayCount"] = 2;
        }
        
    }
 
    protected void gvGuests_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        CheckBox cbDinner = e.Row.FindControl("cbDinner") as CheckBox;
        if (cbDinner != null)
        {
            if ((int)Session["DayCount"] == 1)
            {
                cbDinner.Visible = false;
            }
        }
    }
 
 
=====================================
=====================================
 
 
This shortcut did not work, because it .net tries to set "checked" before testing "visible".  Lame.
 
<EditItemTemplate>
    <asp:CheckBox ID="cbDinner" runat="server" Visible='<%# IsDinnerVisible() %>' Checked='<%# Bind("Dinner") %>' />
</EditItemTemplate>
 
 
    public bool IsDinnerVisible()
    {
        return((int)Session["DayCount"] == 2)
    }

Open in new window

0
 

Author Comment

by:Zernk
ID: 20350112
Correction:  It's not that the field shouldn't databind, since that is the work of the Data Source.  What .net shouldn't do is attempt to render a hidden control and cause an exception when the control is hidden.  That, IMO, is a bug.
0

Featured Post

Increase Agility with Enabled Toolchains

Connect your existing build, deployment, management, monitoring, and collaboration platforms. From Puppet to Chef, HipChat to Slack, ServiceNow to JIRA, Splunk to New Relic and beyond, hand off data between systems to engage the right people.

Connect with xMatters.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question