1

I want to get the checkedlistBox value on variable my code is below can anybody help me

private void CheckPreviousTxn_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            int selected = CheckPreviousTxn.SelectedIndex;
            string selecteditem1 = CheckPreviousTxn.CheckedItems.ToString();
            if (selected != -1)
            {
                foreach (string slecteditem in CheckPreviousTxn.CheckedItems)
                {
                    con = new SqlConnection(connectionpath);
                    cmd = new SqlCommand("select QTNCode as 'QTN Code',STKCODE as 'Item Code',STKDESCP as 'Item Name',Quantity,BaseUnit as 'Unit',Rate,DiscountAmount as 'Discount',Amount,VatPercentage as 'VAT %',TotalTaxAmount as 'VAT Amt' from Tbl_QTNDetail where QTNCode ='" + slecteditem + "'", con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    GrdQtnDetail.DataSource = dt;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

i am getting the following exception

Unable to cast object of type 'System.Data.DataRowView' to type 'System.String'

and I am getting the checkedlistBox
value = {System.Windows.Forms.CheckedListBox, Items.Count: 13, Items[0]:QTN0001}

MindSwipe
  • 7,193
  • 24
  • 47
  • `string selecteditem1 = CheckPreviousTxn.CheckedItems.ToString();` is the problem. `CheckedItems` returns a collection and you need to iterate over that to extract all strings. – Fang Dec 11 '18 at 12:21
  • Off-topic: Your code is vulnerable to SQL Injection. – Reza Aghaei Dec 11 '18 at 20:08
  • To get the item text, use `GetItemText` method of the `CheckedListBox`. To get the item value, use [`GetItemValue`](https://stackoverflow.com/a/38305363/3110834) extension method. – Reza Aghaei Dec 11 '18 at 20:11

2 Answers2

2

The CheckedItems is not a collection of type String. You need to use ListItem or use the Object like:

 foreach (ListItem selecteditem in CheckPreviousTxn.CheckedItems)
 {
    string itemValue = selectedItem.Value;
    string itemText = selectedItem.Text;
    string item = selectedItem.ToString();
    // use it in query
 }

or:

foreach(object itemChecked in checkedListBox1.CheckedItems) 
{
   string selectedItem= itemChecked.ToString();
}

See the DOCS here for reference.

Side Note:

Don't do string concatenation for queries. Consider using parameterized queries as your application is vulnerable to sql injection with string concatenated queries.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Isn't `ListItem` coming from `PresentationFramework`? In `WinForms`, you usually get the item (object) text with `string itemText = checkedListBox1.GetItemText(checkedListBox1.Selecteditem);` – Jimi Dec 11 '18 at 14:02
  • @Jimi not sure it's been so long when worked on winforms but yeah `object` is the base type so should work – Ehsan Sajjad Dec 11 '18 at 14:03
  • Well, I'm talking about this: `foreach (ListItem selecteditem in CheckPreviousTxn.CheckedItems) { }`. and this: `string itemValue = selectedItem.Value;`. Is there a `.Value` property? – Jimi Dec 11 '18 at 14:04
  • It's not valid for Windows Forms. Even the `itemChecked.ToString()` will show `System.Data.DataRowView` for this question. – Reza Aghaei Dec 11 '18 at 20:06
  • CheckPreviousTxn.GetItemText(CheckPreviousTxn.CheckedItems); checkedlistbox id is CheckPreviousTxn i am geting the value is CheckPreviousTxn | {selectedItem="QTN0007"} Qtn0007 is the value i want to get CheckPreviousTxn ="Qtn0007 " – SherifClement Dec 12 '18 at 05:35
0

One more thing if you fill datatable inside for loop you only get the last checkeditem values datatable. If you want all chechked items in one datatable either you create datatable before for loop and add new datas to this datatable :

    DataTable dtBig = new DataTable();
    foreach (ListItem selecteditem in CheckPreviousTxn.CheckedItems)
    {
       con = new SqlConnection(connectionpath);
       cmd = new SqlCommand("select QTNCode as 'QTN Code',STKCODE as 'Item Code',STKDESCP as 'Item Name',Quantity,BaseUnit as 'Unit',Rate,DiscountAmount as 'Discount',Amount,VatPercentage as 'VAT %',TotalTaxAmount as 'VAT Amt' from Tbl_QTNDetail where QTNCode ='" + selectedItem.ToString()+ "'", con);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       da.Fill(dt);
       dtBig.Add(dt);
  }
  GrdQtnDetail.DataSource = dtBig;

or you can try in clause in sql which is better for performance:

string[] items = CheckPreviousTxn.CheckedItems.OfType<object>().Select(item => item.ToString()).ToArray();
string resultItems = string.Join("','", items);
con = new SqlConnection(connectionpath);
cmd = new SqlCommand("select QTNCode as 'QTN Code',STKCODE as 'Item Code',STKDESCP as 'Item Name',Quantity,BaseUnit as 'Unit',Rate,DiscountAmount as 'Discount',Amount,VatPercentage as 'VAT %',TotalTaxAmount as 'VAT Amt' from Tbl_QTNDetail where QTNCode IN ('" + resultItems+ "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GrdQtnDetail.DataSource = dt;
Serhat Oz
  • 788
  • 8
  • 12