简体   繁体   English

设置SelectedValue后,C#列表框值为空

[英]C# Listbox Value is Null After Setting SelectedValue

I have created a listbox based on a database table where the DisplayMember items of the listbox are created via string concatenation and the ValueMember items represents the bigInt PK from the table. 我已经基于数据库表创建了一个列表框,其中该列表框的DisplayMember项是通过字符串串联创建的,而ValueMember项则表示该表中的bigInt PK。 The listbox is bound to a Text/Value object as shown below. 列表框绑定到“文本/值”对象,如下所示。

List<ComboSearchItems> csi = new List<ComboSearchItems>();
     foreach(var i in q)
     {
          ComboSearchItems ci = new ComboSearchItems(String.Concat(i.Id, " - ", i.Name, " - ", i.CompanyName), i.Id);
          csi.Add(ci);
     }

     lstCompany.DataSource = csi;
     lstCompany.DisplayMember = "Text";
     lstCompany.ValueMember = "Value";
     lstCompany.SelectedIndex = 0;
     lstCompany.Refresh();

public class ComboSearchItems
{
    public string Text { get; set; }
    public Int64 Value { get; set; }

    //Constructor
    public ComboSearchItems(string t, Int64 v)
    {
        Text = t;
        Value = v;
    }
}

The listbox is populated and displays correctly but when I attempt to set the SelectedValue property via the code below the listbox's SelectedValue changes to null. 列表框已填充并正确显示,但是当我尝试通过列表框的SelectedValue下面的代码设置SelectedValue属性时,将其更改为null。

 lstCompany.SelectedValue = 16844;

When setting the SelectedValue of a listbox whose value are integers the new value must be of the same type of integer. 当设置其值为整数的列表框的SelectedValue时,新值必须为相同的整数类型。 Attempting to set an Int64 value without explicitly sending an Int64 type will result in a silent failure which causes the listbox's SelectedValue to be set to null. 尝试在不显式发送Int64类型的情况下设置Int64值将导致无提示失败,从而导致列表框的SelectedValue设置为null。

The following examples will set the SelectedValue 以下示例将设置SelectedValue

 lstCompany.SelectedValue = Convert.ToInt64(4251);

 lstCompany.SelectedValue = 4251L;

The following code will silently fail and set the listbox's SelectedValue to null 以下代码将自动失败,并将列表框的SelectedValue设置为null

 lstCompany.SelectedValue = 4251;

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

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