Solved

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

Posted on 2007-11-20
5
1,742 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
  • 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

911 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now