How set value in ASP.NET DataGrid template column?

R

Ronald S. Cook

In my ASP.NET DataGrid, I would like to set the "Selected" value of a
dropdown list item depending on a condition. While this is easy to do for,
say, a textbox, .NET doesn't seem to play as nice in a dropdownlist.

In the below I get the error
Compiler Error Message: CS0117: 'System.Web.UI.WebControls.ListItem' does
not contain a definition for 'DataBinding'

<asp:TemplateColumn HeaderText="Ver">
<HeaderStyle HorizontalAlign="Center" Width="50px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:Label id=lblVersion runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.Version") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="ddlVersion" runat="server">
<asp:ListItem Value="2.2">2.2</asp:ListItem>
<asp:ListItem Value="3.0" Selected="<%# IsThree(3)% >3.0</asp:ListItem>
<--- ERROR LINE
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>


public bool IsThree(int intNumber)
{
if (intNumber == 3)
return true;
else
return false;
}


Any thoughts?

Thanks,
Ron
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Ronald,

I see only one " in the selected attribute, remove it and see what happen

Cheers,
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Ronald,

It seems that you cannot use DataBinding with a ListItem , if you see the
MSDN ListItem derived directly from System.Object in order to be bindable
you need to derived from WebControl or implement the IDataBindingAccessor ,
its this latter interface which define the DataBindings property ( the
source of the error)

Solution:
1- Inherit from ListItem and implement IDataBindingAccessor interface
2- Do it by code, iterate in the DropDownList.Items collection and set the
correct DropDownList.SelectedIndex

I would go for the second one.


Hope this help,
 
S

Steven

I think your problem is in this line

<asp:Label id=lblVersion runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.Version") %>'>

Your DataBinder syntax is incorrect. It should be

<asp:Label id="lblVersion" runat="server "Text='<%#
DataBinder.Eval(Container.DataItem, "Whatever") %>' />

Specifically, note the change from

DataBinder.Eval(Container, "DataItem.Version")

TO

DataBinder.Eval(Container.DataItem, "Whatever")
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Steven,

Yes, that's another error but no the one that he is getting, the thing is
that you cannot use databinding with a ListItem element.

Cheers,
 

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

Top