Solved

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

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

813 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

14 Experts available now in Live!

Get 1:1 Help Now