我如何从下拉列表中获取一个值,并在事件更改时编写一个事件? [英] how can i get a value from dropdownlist and write an event for when it change?

查看:58
本文介绍了我如何从下拉列表中获取一个值,并在事件更改时编写一个事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void dpdCourse_SelectedIndexChanged(object sender, EventArgs e)
   {
       string name = dpdCourse.SelectedItem.Value;
       var crs = DB.Courses.Where(c => c.Name == name).First();
       crsCode.Text = crs.Id.ToString();

   }



我在从调试母版页派生的页面中为下拉列表编写了此代码,当我调试此页面时,到达此事件的开始时,它转到母版页的page_load并得到此错误:

输入的字符串格式不正确.

谢谢.



i wrote this code for a dropdown list in a page that is derived from a master page when i debug this page when arrive at the beginning this event it goes to page_load of master page and get this error:

Input string was not in a correct format.

thank you.

推荐答案

我相信这里发生了几件事情.首先,首次加载页面时会触发此事件.这个是正常的.但是,下拉菜单的值尚未设置,因此会出现错误.第二个问题是您正在尝试立即触发此事件,但是我不相信会发生这种情况,因为此代码是服务器端的.除非您执行POST,否则您不会看到事件触发.相反,您需要使用类似jQuery的东西来处理事件.

例如,在jQuery中,您可以编写以下部分:

There are a couple things going on here, I believe. First, this event is firing when you first load the page. This is normal. However, your value for the drop down is not yet set, so you get an error. The second issue is that you are trying to fire this event right away, but I don''t believe that will happen because this code is server-side. Unless you do a POST, you won''t see the event fire. Instead, you need to use something like jQuery to handle your events.

For example, in jQuery, you could write the following section:


(" span>).change(函数(){ <在此处触发您的事件> });
("#dropdownID").change(function () { <fire your event here> });



只要确保将其放入DOM ready事件中,就不会过早触发该事件.

要了解有关jQuery change事件的更多信息并查看一个非常类似于您的HTML代码的工作示例,请参见: http://api.jquery.com/change/ [ ^ ]

请注意,这与ASP.NET/C#代码无关.实际上,如果实现此方法,则应从代码中完全删除事件.由于该事件仅在服务器操作(页面加载,POST,GET)之后才会触发,因此无论如何它不会做您想要的事情.



Just make sure you put that inside the DOM ready event so it doesn''t fire prematurely.

To learn more about the jQuery change event and to see a working example that will look a lot like your HTML code, look here: http://api.jquery.com/change/[^]

Please note that this has nothing to do with ASP.NET/C# code. In fact, if you implement this method, you should remove your event entirely from your code. Since that event will only fire after a server action (page load, POST, GET), it won''t do what you want anyway.




我的东西,这是由于转换错误. crs.Id.ToString()引发错误.可能是crs为空.如果为null,则crs.Id.ToString()将出现错误.使用Convert.ToString(crs.Id).这可以处理空异常.
Hi,

I thing, it is due to the casting error. crs.Id.ToString() is throwing the error. May be crs will be null. If it is null, crs.Id.ToString() will through error. Use Convert.ToString(crs.Id). This can handle null exception.


这篇关于我如何从下拉列表中获取一个值,并在事件更改时编写一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆