开发者

Using DropDownList in EditTemplates of a GridView

I am working on a GridView in Asp.Net. When initially a the Page Loads, my gridview look like: alt text http://www.freeimagehosting.net/uploads/e45e5b66d4.jpg

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 开发者_JAVA技巧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 http://www.freeimagehosting.net/uploads/7d3f6ba9a5.jpg

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.


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>


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜