Solved

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

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Default parameter problem in C# 3 26
Wpf develop 5 30
Need to Modify a Script I found 5 77
Saveas need to save a copy 16 0
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

707 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

16 Experts available now in Live!

Get 1:1 Help Now