简体   繁体   English

在GridView的EditTemplates中使用DropDownList

[英]Using DropDownList in EditTemplates of a GridView

I am working on a GridView in Asp.Net. 我正在使用Asp.Net中的GridView。 When initially a the Page Loads, my gridview look like: alt text http://www.freeimagehosting.net/uploads/e45e5b66d4.jpg 最初页面加载时,我的gridview看起来像: 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. 当用户单击,编辑行时,我使用编辑模板在DropDownList中显示“域”。 But problem is , when the DropDownlist gets load with data, it lost the current value of the 'Domain'. 但问题是,当DropDownlist加载数据时,它会丢失“域”的当前值。
ie 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. 如果我想编辑第4行,其当前设置为“计算机”的域将变为“MBA” ,这当然是DataSource返回的第一个元素。 alt text http://www.freeimagehosting.net/uploads/7d3f6ba9a5.jpg alt text http://www.freeimagehosting.net/uploads/7d3f6ba9a5.jpg


I want to display the current value ('computers') as the selected value in DropDownList. 我想在DropDownList中显示当前值('computers')作为选定值。 But I am unable to get the value of Domain, which is being edited. 但是我无法获得正在编辑的Domain的值。

You can bind the SelectedValue property of the dropdown as in: 您可以绑定下拉列表的SelectedValue属性,如下所示:

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: 编辑:如果该值不存在,则不幸的剩余解决方案将进入gridview的RowDataBound并获取对下拉的引用,并执行:

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. 如果没有选择项目,请尝试ddl.SelectedValue = item.Value。

HTH. HTH。

to solve exception use AppendDataBoundItems="true". 解决异常使用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>

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. 监听事件RowEditing,使用.FindControl()方法获取特定行的Dropdownlist,并在DDL上执行显式.DataBind()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM