我有 checkedlistBox,我想获取所选项目的 valuemember 和显示成员 c#

I have checklistBox and I want to get the selected item's valuememebr and display member c#

我有一个清单框,用户可以在其中 select 多个项目,我必须遍历整个列表并检查选中的项目:

foreach (var itemChecked in chklistCurrency.CheckedItems)
{
    var row = (itemChecked as DataRowView)?.Row;
    // ...
}

我尝试单独使用数据行视图和数据行,但在空值引用中出现错误

这是我的另一个代码,但 Value 和 DisplayMember 是红线

foreach (var itemChecked in chklistCurrency.CheckedItems)
{
    var cra = new CurrencyAccount();
    cra.CurrencyName = itemChecked.ValueMember;
    cra.CurrencySymbol = itemChecked.DisplayMember;  
    // ...
}


DataSource of the checklist was inserted like this 

   var currency = db.currencies.ToList();
            foreach (var item in currency)
            {
                chklistCurrency.DisplayMember = item.currencyName;
                chklistCurrency.ValueMember = item.currencySymbol;                
                chklistCurrency.Items.Add(item.currencyName);
            }

你可以这样做。

foreach(var item in checkedListBox1.CheckedItems)
{   
     DataRowView row = (item as DataRowView).Row;
     currencyaccount cra = new currencyaccount();
     cra.currencyName = row["currencyName"];
     cra.currencySymbol = row["currencySymbol"];  
}

以下着重于提供来自 CheckedListBox 的已检查项目列表,其中 DataTable 作为数据源。

Project 在 GitHub 存储库中(在 C#9 中完成,但扩展来自 .NET Framework,这意味着它们可以在任何版本的 .NET Framework 中工作)。

select 语句的片段

#region So there is no guessing when working with data in the form
/// <summary>
/// Product table primary key <see cref="ReadProductsTask"/>
/// </summary>
public static readonly string PrimaryKey = "ProductID";
/// <summary>
/// What to display in CheckedListBox
/// </summary>
public static readonly string DisplayColumn = "ProductName";
#endregion

/// <summary>
/// Responsible for reading products in 
/// </summary>
/// <returns></returns>
private static string SelectStatement()
{
    return $"SELECT P.{PrimaryKey}, P.{DisplayColumn}, P.SupplierID, S.CompanyName, P.CategoryID, " +
           "C.CategoryName, P.QuantityPerUnit, P.UnitPrice, P.UnitsInStock, P.UnitsOnOrder, " +
           "P.ReorderLevel, P.Discontinued, P.DiscontinuedDate " +
           "FROM  Products AS P INNER JOIN Categories AS C ON P.CategoryID = C.CategoryID " +
           "INNER JOIN Suppliers AS S ON P.SupplierID = S.SupplierID";
}

Class获取勾选项

public class ProductItem    
{
    public int Identifier { get; set; }
    public string ProductName { get; set; }
    public int Index { get; set; }
    public override string ToString() => ProductName;
}

获取勾选项的扩展方法

public static List<ProductItem> ProductSelectedList(this CheckedListBox sender, string primaryKeyName)
{
    return
    (
        from item in sender.Items.Cast<DataRowView>()
            .Select(
                (data, index) =>
                    new ProductItem
                    {
                        Index = index,
                        Identifier = data.Row.Field<int>(primaryKeyName),
                        ProductName = data.Row.Field<string>("ProductName")

                    }
            )
            .Where((x) => sender.GetItemChecked(x.Index))
        select item
    ).ToList();
}

用于在表单 Shown 事件中加载 CheckedListBox 的表单代码

DataTable table = await DataOperations.ReadProductsTask(_cancellationTokenSource.Token);

ProductCheckedListBox.DataSource = table;
ProductCheckedListBox.DisplayMember = DataOperations.DisplayColumn;

按钮点击事件获取勾选项

private void GetCheckedProductsButton_Click(object sender, EventArgs e)
{
    List<CheckedListBoxExtensions.ProductItem> results =
        ProductCheckedListBox.ProductSelectedList(DataOperations.PrimaryKey);

    if (!results.Any()) return;
    StringBuilder builder = new();

    foreach (var item in results)
    {
        builder.AppendLine($"{item.Identifier}, {item.ProductName}");
    }

    textBox1.Text = builder.ToString();

}

截图

checkedlistbox源数据代码

   string mainconn = (helper.CnnVal("poscon"));
            SqlConnection sqlconn = new SqlConnection(mainconn);
            string sqlquery = "select currencyName,currencySymbol from [dbo].[currency]";
            SqlCommand sqlComm = new SqlCommand(sqlquery, sqlconn);
            sqlconn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(sqlComm);
            System.Data.DataTable dt = new System.Data.DataTable();
            sda.Fill(dt);
            this.chklistCurrency.DataSource = dt;
            ((System.Windows.Forms.ListBox)chklistCurrency).DisplayMember = "currencyName";
            ((System.Windows.Forms.ListBox)chklistCurrency).ValueMember = "currencySymbol";

正在使用此代码检索选中的项目

  foreach (var itemChecked in chklistCurrency.CheckedItems)
                {
                    currencyaccount cra = new currencyaccount();
                    var row = (itemChecked as DataRowView).Row;                    
                    cra.currencyName = row.Field<string>("currencyName");
                    cra.currencySymbol = row.Field<string>("currencySymbol");
                    cra.accountId = at.accountId;
                    db.currencyaccounts.Add(cra);
                    db.SaveChanges();                       
                }