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
Solved

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

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

809 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