views:

107

answers:

1
+1  Q: 

gridview dropbox

I'm trying to use a GridView to display a list of components in ASP.NET. I'm trying to make it editable at the same time. One of the columns is a string that should be selected out of a list when the user edits the row.

So I've tried the following:

  1. Convert the BoundField row to an ItemTemplate
  2. Add a dropbox to the template window in the gridview
  3. bound the selecteditem to the string

At this point, I get an error because the list items haven't been set up in the dropbox. So I guess the two things I'm wondering are:

  1. How do I assign the items in the dropbox to a dynamically created list of options?
  2. How do I make the dropbox only appear when the row is being edited?

Ok so I've discovered the "EditItemTemplate" field in visual studio, that answers #2.

And now I've discovered that the dropbox has a datasource field which can be linked to a property in the data object, and that holds the options list.

A: 

In your DropDownList you can assign a OnDataBinding event and then us the event to fill your DropDownList with custom data.

Example:

<Columns>
    <asp:TemplateField>
        <EditItemTemplate>
            <asp:DropDownList ID="yourDropDownList" runat="server"
                DataTextField="YourTextFieldName" DataValueField="YourValueFieldName"
                OnDataBinding="yourDropDownList_DataBinding"></asp:DropDownList>
        </EditItemTemplate>
    </asp:TemplateField>
</Columns>

Then in your code behind implement the OnDataBinding:

protected void yourDropDownList_DataBinding(object sender, System.EventArgs e) 
{ 
    DropDownList ddl = (DropDownList)(sender);
    // GetMyDropDownListData should return cached data so your not hitting your DB
    // each time. You can customize the data for each row here. Use the Eval command
    // to access the current rows databound values.
    ddl.DataSource = GetMyDropDownListData();
    ddl.DataBind();  // Now all the options will be loaded

    // Set the current field's selected value
    ddl.SelectedValue = Eval("YourSelectedValueFieldName").ToString();
}

Hope that helps.

Kelsey