如何在绑定之前更改 DropDownList 的 SelectedValue?
基本上,我有一个 Customers
表,其中一个字段是 Gender
,我正在制作一个表单,允许用户更新客户信息,在本例中为性别。 Gender 的默认 SelectedValue 是“Male”或“Female”,我想在实际将其绑定到数据库之前将“Male”更改为 0,将“Female”更改为 1。我将其作为我的代码:
protected void fmvCustomerDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
if (fmvCustomerDetails.editGender.val.Equals("Male"))
fmvCustomerDetails.editGender.val = 0;
}
fmvCustomerDetails 是我的 FormView 对象的 ID,editGender 是 DropDownList 的 ID。由于解释起来太麻烦的原因,我不能只是更改数据库以接受“男性”或“女性”作为输入。
Basically I have a Customers
table with one of the fields being Gender
, and I'm making a form that allows the user to update the customer information, in this case the gender. The default SelectedValue for Gender is either "Male" or "Female" and I want to change "Male" to 0 and "Female" to 1 before actually binding it to the database. I got as far as having this as my code behind:
protected void fmvCustomerDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
if (fmvCustomerDetails.editGender.val.Equals("Male"))
fmvCustomerDetails.editGender.val = 0;
}
fmvCustomerDetails is the ID of my FormView object and editGender is the ID of the DropDownList. For reasons that is too troublesome to explain, I can't just change the database to accept "Male" or "Female" as the input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您能否更改 DropDownList 中的项目,使文本为“Male”且值为“0”?
Can you change the items in your DropDownList so that the text is "Male" and the value is "0"?
我找到了解决此问题的解决方法,因此我将删除此问题。
我将其标记为答案,因为显然我需要有一个接受的答案才能删除我的问题。 (诡异的)
I've found a workaround that circumvents this problem, therefore I'll be deleting this question.
I'm marking this as the answer as apparently I need to have an accepted answer before I can delete my question. (weird)
假设您使用的是组合框(DropDownList 只是 ComboBox 类的 DropDownStyle),您应该使用 DisplayMember 作为性别(男、女),使用 ValueMember 作为 0 和 1。
这样,您就不必在推送到数据库之前执行任何更改值的技巧。您只需绑定您的字段即可。
您可以创建一个 ArrayList,其中包含所需的值和要显示的字符串。然后将值绑定到 ValueMember,将字符串绑定到 DisplayMember。
如果您想获取与 DropDownList 关联的数字,可以通过 SelectedValue 获取。
Assuming you're using a combobox (DropDownList is only the DropDownStyle of the ComboBox class), you should use the DisplayMember to be the gender (male, female) and ValueMember to be the 0 and 1.
This way, you won't have to do any trick changing values before pushing to your database. You can just bind your field.
You could create an ArrayList that contains both the value wanted and the string you want to display. Then bind the value to the ValueMember and the string to the DisplayMember.
If you want to get the number associated with your DropDownList you can get it through SelectedValue.