How to Bind a DropDownList control to a DataGrid in Template Column?

J

Jeff Petter

I'm having a tough time with this, and I can't find any resources that address it. I have a DataGrid comprised of Template Columns, in which I have both TextBox and DropDownList controls. The purpose of the DataGrid is to allow users to edit previously made selections, and I am using a DataSet and a DataView to load the XML data into. The idea is so that when the grid loads, it is populated with the data from the XML source. It works great for the TextBoxes, but I can't get the syntax down right for the DropDownList controls. Depending upon how I edit the code, I either get an error informing me that the control doesn't exist in the namespace, which it clearly does. Or I get the list items: one letter per row, in the box. In my previous and limited experience with asp.net, I've done all my binding in the "code behind" page, but all the examples I saw embedded the code in the HTML code, so that is what I've done.

Here is one binding statement:
<asp:DropDownList id=ddExceptions runat="server" DataSource='<%# DataBinder.Eval(Container, "DataItem.exception") %>' Width="173px"> - This results in displaying the list items, but only one letter per row. So, I decided to try the SelectedIndex property and have the binding statement:
<asp:DropDownList id=ddExceptions runat="server" SelectedIndex='<%# ddExceptions.SetIndex(DataBinder.Eval(Container, "DataItem.exception")) %>' Width="173px">
This results in error essages stating that 'ddExceptions' does not exist in the namespace. And I've played with the syntax for over a day, all to no avail. Does anyone know ANY way to do this, or have any ideas that I might try?

I appreciate it a bunch. BTW, FWIW, the code is in c#.

Thanks,
Jeff
 
Y

Ying

Hi,

In your "code behind" page, implement the ItemDataBound event for your
grid.

private void MyDataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if ( e.Item.FindControl( "ddExceptions" ) != null )
{
DropDowList ddlExc = ( DropDownList)e.Item.FindControl(
"ddExceptions" );
ddlExc.DataSource = yourListOfExceptions;
ddlExc.DataTextField = "Exception";
ddlExc.DataBind();
if( e.Item.DataItem is DataRowView )
{
ddlExc.SelectedIndex = ddlExc.Items.IndexOf(
ddlExc.Items.FindByText(
((DataRowView)e.Item.DataItem).Row["exception"].ToString()));
}
}
}

Best regards,

Ying
 

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

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top