I Fill Check List Box From Database Using Store Procedure Like This:
I am Trying To Get The Display Member And The Value Member For The Checked Items Only And Put Them In Data Grid View.
But The Value Member Show For The First Checked Item Only And The Display Member Show The Store Procedure Name
Is There Any One Can Help
`int id3 = Convert.ToInt32(cbx_MainItemFilter.SelectedValue);
int id4 = Convert.ToInt32(cbx_MainCostDriver.SelectedValue);
var q3 = db.SP_SelectDriverItem().Where(s => s.MainCostDriverID == id4 &&
s.MainCostItemID == id3);
clb_SubItems.DataSource = q3.ToList();
clb_SubItems.DisplayMember = "SubCostItemName";
clb_SubItems.ValueMember = "SubCostItemID";`
private void btn_ShowDetails_Click(object sender, EventArgs e) {
for (int i = 0; i < clb_SubItems.Items.Count; i )
{
if (clb_SubItems.GetItemChecked(i))
{
dgv_BOQItems.Rows.Add(clb_SubItems.Items[i]);
}
}
}
CodePudding user response:
Consider loading data from your database into a list, in the class override ToString
to what column/property you want to show in the CheckedListBox.
Simple example use the following class.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
Keeping simple, use mocked data which in your case comes from your stored procedure.
public class Mocked
{
public static List<Company> Companies => new List<Company>()
{
new Company() {Id = 1, Name = "A"},
new Company() {Id = 2, Name = "B"},
new Company() {Id = 3, Name = "C"},
};
}
In your form, assign the DataSource for the CheckedListBox to the mocked data above in say form Shown event or button click.
checkedListBox1.DataSource = Mocked.Companies;
Language extension to use in the next code block
public static class CheckedListBoxExtensions
{
public static List<Company> CheckedList(this CheckedListBox source)
=> source.Items.Cast<Company>()
.Where((item, index) => source.GetItemChecked(index))
.Select(item => item)
.ToList();
}
Get checked items, here in a button click event, here we have access to all checked items.
private void CheckedCompanyButton_Click(object sender, EventArgs e)
{
var result = checkedListBox1.CheckedList();
if (result.Count <= 0) return;
foreach (var company in result)
{
Console.WriteLine($"{company.Id, -5}{company.Name}");
}
}
CodePudding user response:
thank you for your help i Got A solution for This But It Still Has Simple Problem That It Duplicate The Result
private void btn_ShowDetails_Click(object sender, EventArgs e)
{
for (int i = 0; i < clb_SubItems.Items.Count; i )
{
if (clb_SubItems.GetItemChecked(i))
{
foreach (var item in clb_SubItems.CheckedItems.OfType<SP_SelectDriverItem_Result>())
{
dgv_BOQItems.Rows.Add( clb_SubItems.GetItemText(clb_SubItems.Items[i]), item.SubCostItemID);
}
}
}
}