简体   繁体   English

列表框中的C#SelectedValue

[英]C# SelectedValue in a Listbox

I'm adding data to my listbox using this code : 我正在使用以下代码将数据添加到我的列表框中:

    SqlCommand cmd1 = new SqlCommand("SELECT U_Naam, U_Voornaam, User_ID FROM Login ORDER BY U_Naam ASC", con);
    dr = cmd1.ExecuteReader();

    int teller = 0;

    while (dr.Read())
    {
        hulp = dr["U_Naam"].ToString() + " " + dr["U_Voornaam"].ToString();
        lbNiet.Items.Add(hulp);
        lbNiet.Items[teller].Value = dr["User_ID"].ToString();
        teller++;
    }

When I run the program and select an item in the list I want to get it's value (Using selectedvalue). 当我运行程序并在列表中选择一个项目时,我想获取它的值(使用selectedvalue)。 When I do this it allways gives a nullref (no value). 当我这样做时,它总是给出一个nullref(无值)。 I've read somewhere the selected item is lost after a postback ? 我读过某个地方,回发后所选项目丢失了吗? How can I solve this ? 我该如何解决?

thanks ! 谢谢 !

I don't think the selected item is lost after PostBack under normal circumstances - my guess is that you are accidently populating the ListBox again after PostBack so that when you make a selection, the system hits the Page_Init / Page_Load (or whatever event you choose to populate the ListBox in) and recreates all the options. 我认为正常情况下在PostBack之后选择的项目不会丢失-我的猜测是您不小心在PostBack之后再次填充了ListBox,因此,当您进行选择时,系统会按Page_Init / Page_Load(或您选择的任何事件)以填充列表框)并重新创建所有选项。 Doing this would overwrite the currently selected option. 这样做会覆盖当前选择的选项。

If that's the case it's easily avoided by check for PostBack first before repopulating the list. 如果是这种情况,可以通过在重新填充列表之前先检查PostBack来轻松避免。

replace these lines 替换这些行

lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();

with

lbNiet.Items.Add(new ListItem(hulp,dr["User_ID"].ToString();));

Are you running that code in the Load of your ASP.NET page without checking to see if it is a Postback? 您是否在ASP.NET页面的“加载”中运行该代码,而没有检查它是否是回发? You should make sure to wrap your loading code in a if (!IsPostback) {} block if you're doing it in the load of the page. 如果要在页面加载中进行加载,则应确保将加载代码包装在if (!IsPostback) {}块中。

对数据进行数据绑定而不是添加循环会有所帮助。

Are you using the ViewState for your page? 您是否为页面使用ViewState?

If yes, check the IsPostBack property of the page, and don't populate your list after postback. 如果是,请检查页面的IsPostBack属性,并且回发后不要填充列表。

you can use Request.Form to find the posted value 您可以使用Request.Form查找过帐的值
or I think if you use a scriptmanager and an updatepanel it refills the box after a postback 或者我认为,如果您使用脚本管理器和更新面板,则在回发后会重新填充该框

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

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