System.InvalidCastException: Specified cast is not valid.

J

Jimmy

Hi

I get the this error when i run my code:


private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

this.DataGrid1.DataSource= this.DataSource();

this.DataGrid1.DataBind();

}

private ICollection DataSource()

{

DataTable dt = new DataTable();


dt.Columns.Add(new DataColumn("kol0",typeof(Int16)));


for (int i=0;i<10;i++)

{

DataRow dr = dt.NewRow();

if (i%2==0)

{

dr[0]=1;


}

else

{

dr[0]=0;


}

dt.Rows.Add(dr);

}

DataView dv;

dv = new DataView(dt);

return dv;

}

private void DataGrid1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)

{

int i = e.Item.ItemIndex;

if(i==0)

{

((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";

}


}



page:



one two
one two
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 96px; POSITION:
absolute; TOP: 56px" runat="server"
Height="216px" Width="448px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="dll" Runat="server">
<asp:ListItem Value="0">one</asp:ListItem>
<asp:ListItem Value="1">two</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

ch J
 
K

Karl Seguin

It would help if you told us the line #. Is it at:
((DropDownList)e.Item.Cells[0].Controls[0]).SelectedValue="one";

First of all, it looks like you are doing that when ItemIndex == 0
wouldn't that be ur HeaderTemplate in which case cell[0].Controls[0]. really
might not be what you expect. Secondly, you might prefer
e.Item.FindControl("dll") or e.Item.Cells[0].FindContorl("dll") (not sure
which will work, favor the first one if it'll work) over using indexes. It
makes your code more flexible and less likely to break. Sometimes literals
(like spaces and newlines) are converted to controls, so while you might
think it's Controls[0], it might really be Controls[1] 'cuz there was a
newline before it.

It should be pretty easy to step through your code and debug though...

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top