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

313 Views Asked by At

I have a checklistbox where users can select multiple items, I have to go through the whole list and check the checked items:

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

I tried to use datarowview and datarow alone it gives me error in Null value reference

Here is my another code but Value and DisplayMember are in redline

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);
            }
3

There are 3 best solutions below

0
Developer On BEST ANSWER

checklistbox sourse data code

   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";

retrieving the checked item with this code

  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();                       
                }
3
Nihat Çelik On

You can make it like this.

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

The following focuses on providing a list of checked items from a CheckedListBox with a DataTable as the DataSource.

Project in GitHub repository (done in C#9 but the extensions are from .NET Framework meaning they work in any version of the .NET Framework).

Snippet for select statement

#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 for obtaining checked items

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

Extension method for obtaining checked items

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();
}

Form code to load CheckedListBox in form Shown event

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

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

Button Click event to get checked items

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();

}

Screenshot

enter image description here