我在TemplateField
中使用GridView
从数据库中实现edit/delete
。
我使用SqlDataSource
控件查询数据。
当我从页面编辑表格时出现以下错误:
' DropDownList1'有一个SelectedValue,它是无效的,因为它确实如此 项目列表中不存在。参数名称:值
这是因为来自dB的数据与任何DropDownList
国家/地区名称都不匹配。
我理解这个question 的问题(没有给出解决方案!)
我认为当我将数据插入dB时,它会自动为数据添加冗余空格(如国家名称)
因此,一种解决方案是从String中删除空格(Trim),以便在DropDownList
项之一中匹配值。
因为<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("Country")%>'
不匹配DropDownList的任何列表项
但
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("Country").ToString().Trim()%>'>
匹配DropDownList的列表项。
现在我想将数据更新回数据库,而不是存储国家名称空值。
(我认为这是Eval()
)
我可以使用Bind()
将数据更新回dB
但是Bind
并不支持ToString().Trim()
,因此我无法修剪字符串以匹配DropDownList中的某个项目。
如何将数据更新回dB?
我的raw code
答案 0 :(得分:1)
&#34;因此,一种解决方案是从String中删除空格(Trim)以便这样做 值在DropDownList字段中匹配。&#34;
我有点困惑,为什么这会有所作为。
您能否向我们展示此DropDownList控件已创建的原始HTML以及您尝试编辑的行。
查看原始HTML ..
select
元素。展开此元素,以查看option
元素。 你应该看到一个更复杂的版本......
<select id="listOfPeople">
<option value=""></option>
<option value="10">Mike</option>
<option value="17">Geoffery</option>
<option value="18">Edward</option>
</select>
...您看到的错误表明,当您点击其中一行时,其值不会与value
中列出的option
之一相匹配}第
<强>更新强>
查看.aspx文件后,我看到您显示的是国家/地区名称列表,但没有一个具有值:
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("Country").ToString().Trim()%>'>
<asp:ListItem>Select Country</asp:ListItem>
<asp:ListItem>India</asp:ListItem>
<asp:ListItem>USA</asp:ListItem>
<asp:ListItem>UK</asp:ListItem>
<asp:ListItem>China</asp:ListItem>
<asp:ListItem>North Korea</asp:ListItem>
<asp:ListItem>Kazakhstan</asp:ListItem>
</asp:DropDownList>
他们不应该这样......
<asp:ListItem Value="North Korea">North Korea</asp:ListItem>
......而不是......?
<asp:ListItem>North Korea</asp:ListItem>
(再次 - 使用Chrome来检查您的国家/地区名称 的下拉列表中是否包含Value
。如果他们不知道,这将解释您的错误和&#t} #39;重看。)
更新2
我从其他许多提出同样问题的StackOverflow问题中窃取了以下提示:
尝试将以下内容添加到edittemplate
中以查看当前值:
<asp:Label ID="lblCountryName" runat="server" Text='<% #Bind("Country") %>'></asp:Label>
这应该告诉你Value
它试图在DropDownList控件创建的option
项列表中查找并找不到它。
答案 1 :(得分:1)
在抓了几个小时之后,最后,我发现了尾随空间问题的优雅解决方案。
在我的表定义中,在Country
字段定义中,我使用的是nchar(100)
而不是nvarchar(100)
。前者总是有100个字符(因此是尾随空格),后者最多可以有100个字符,但不填充空格(因此匹配DropDownlist
中的项目。)
简而言之,<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Country")%>'>
现在工作正常。
我希望它能帮助未来的读者。
答案 2 :(得分:0)
使用它:
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Convert.ToString(Eval("Country"))%>'>
<asp:ListItem Value="">Select Country</asp:ListItem>
<asp:ListItem Value="India">India</asp:ListItem>
<asp:ListItem Value="USA">USA</asp:ListItem>
<asp:ListItem Value="UK">UK</asp:ListItem>
<asp:ListItem Value="China">China</asp:ListItem>
<asp:ListItem Value="North Korea">North Korea</asp:ListItem>
<asp:ListItemValue="Kazakhstan">Kazakhstan</asp:ListItem>
</asp:DropDownList>