我已经编写了一些代码来进行gridview的批量更新。在gridview中,我的一个模板字段有一个下拉列表:
<asp:DropDownList ID="DDLCategories" runat="server"
DataSourceID="odsCategories" DataTextField="txtCategory"
DataValueField="intCategoryID" SelectedValue='<%# Bind("intCategoryID") %>'>
<asp:ListItem Text="Please Select an item" Value ="-1"></asp:ListItem>
</asp:DropDownList>
在我的数据库中,我有800条记录。但是只有少数几个被赋值为“intCategoryID”。其余的都是NULL。
批量更新的全部原因是更新所有“intCategoryID”字段并为每条记录分配类别ID。
因为并非所有的“intCategoryID”都被指定了值,所以当我尝试渲染页面时,我收到错误。下拉列表失败。以下是信息:
'DDLCategories' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
有没有办法可以将空类别分配给我在下拉列表中创建的值为“-1”的列表项? IE如果“intCategoryID”ISNULL选择了“请选择项目”,否则选择所选值。
答案 0 :(得分:0)
我试图将您指出的代码转换为我,但是我仍然只是C#和ASP.NET的新手,因此我有一些错误。
您指出的代码是指formview,但我想将其更改为gridview。
到目前为止,这是我的代码:
protected void GridView1_PreRender(object sender, EventArgs e)
{
DataRowView rowView = (DataRowView)(GridView1.DataItem);
if ((rowView != null) &&
((DropDownList)(GridView1.FindControl("DDLCategories")).Items.FindByValue(rowView["intCategoryID"].ToString()) != null));
{
(DropDownList)(GridView1.FindControl("DDLCategories")).SelectedValue = rowView["Category"].ToString();
}
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
e.NewValues["intCategoryID"] = (DropDownList)(GridView1.FindControl("DDLCategories")).SelectedValue;
}
当我创建错误时,请指出。
答案 1 :(得分:0)
最简单的方法是允许AppendDataBoundItems并添加一个对应于null的intem。它可以具有值“-1”或您不在列表值上的任何其他值。现在你所要做的就是做一个条件绑定:
(Eval("intCategoryID") != null && Eval("intCategoryID").ToString().Length>0) ? Eval("intCategoryID").ToString() : "-1"
答案 2 :(得分:0)
要解决此问题,您可以创建自定义DropdownList服务器控件。
using System.Web.UI.WebControls;
namespace CustomNamespace
{
// Dropdownlist which does not throw an exception if SelectedValue does not exist
public class CustomDropdownList : DropDownList
{
protected override void PerformDataBinding(System.Collections.IEnumerable dataSource)
{
try
{
base.PerformDataBinding(dataSource);
}
catch (System.ArgumentOutOfRangeException)
{
}
}
}
}
然后使用aspx页面上的自定义下拉列表。如果您的项目被调用&#34; CustomProject&#34;,请在aspx文件的第二行添加:
<%@ Register assembly="CustomProject" namespace="CustomNamespace" tagprefix="custom" %>
然后将所有DropdownList标记实例替换为自定义标记实例:
<custom:CustomDropdownList ID="ddlId" runat="server" SelectedValue='<%# Bind("column") %>' DataSourceID="dataSourceDropdown" DataTextField="field" DataValueField="value" />
答案 3 :(得分:-1)
结帐this post。它会覆盖DDL的绑定方法并检查缺少的SelectedValue。如果你没有使用FormView,你可能需要修改它,但我认为你将在这篇文章中有一个良好的开端。