views:

368

answers:

3

I am working on a GridView in Asp.Net. When initially a the Page Loads, my gridview look like: alt text

When a user clicks, to edit a row, I am using edit templates to show 'Domain' in a DropDownList. But problem is , when the DropDownlist gets load with data, it lost the current value of the 'Domain'.
i.e If I want to edit 4th Row, its domain which is currently set to 'Computers' is getting changed to 'MBA' which is ofcourse the first element return by the DataSource. alt text


I want to display the current value ('computers') as the selected value in DropDownList. But I am unable to get the value of Domain, which is being edited.

+1  A: 

Hey,

You can bind the SelectedValue property of the dropdown as in:

SelectedValue='<%# Eval("Domain") %>'

However, if you bind a value that doesn't exist, an exception will be thrown. So you may need to handle in code depending on your scenario.

EDIT: if the value doesn't exist, the unfortunate remaining solution will be tap into the gridview's RowDataBound and get the reference to the drop down, and do:

MyBoundObject obj = (MyBoundObject)e.Row.DataItem;
DropDownList ddl = (DropDownList)e.Row.Cells[<index>].FindControl("ddl1");
ListItem item = ddl.Items.FindByValue(obj.Domain);
if (item != null) item.Selected = true;

Here, only if the list item exists it is selected. If that doesn't select the item, try ddl.SelectedValue = item.Value.

HTH.

Brian
Yes, I tried it, but got an exception, that current value does'nt exist in the list. What to do.
vaibhav
Handle it in code is the only other solution. Will edit above.
Brian
@Brian Thanks a lot for the code.
vaibhav
+1  A: 

to solve exception use AppendDataBoundItems="true".

<asp:DropDownList ID="ddlCategory" runat="server" SelectedValue='<%# Eval("Domain") %>' 
        DataSourceID="datasource"
            DataTextField="text" DataValueField="value" AppendDataBoundItems="true">
            <asp:ListItem Text="Select..." Value=""></asp:ListItem>
        </asp:DropDownList>
Saar
@Saar Thanks, It worked for me, but I have to take DomainId as the SelectedValue.:)
vaibhav
you're welcome.
Saar
A: 

This may help you:

Listen to the event RowEditing, get the Dropdownlist of the specific row using the .FindControl() Method and perform an explicit .DataBind() on the DDL.

citronas