0

そのため、チェックボックスの値メンバーを取得しようとしているcheckListBoxがあります。現在、1つのアイテムのselectedValueを取得できます。複数の項目がチェックされている場合、それぞれに対して同じselectedValueを取得します。

ボックスは次のように入力されます...

SqlConnection cn = new SqlConnection(Properties.Settings.Default.cs);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("usp_getCustomers, cn);
DataSet ds = new DataSet();
da.Fill(ds, "usp_getCustomers");
chkListCustomer.DataSource = ds;
chkListCustomer.DisplayMember = "usp_getCustomers.name";
chkListCustomer.ValueMember = "usp_getCustomers.id";
chkListCustomer.SelectedIndex = -1;

ボタンをクリックすると、これは私が試して選択した値を取得するために行っていることです。1つのアイテムに適切なIDが与えられますが、複数のアイテムがチェックされている場合は、すべてに同じIDが返されます。

foreach (int indexChecked in chkListCustomer.CheckedIndices)
{
    MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" + chkListCustomer.SelectedValue.ToString()  + ".");   
}

出力例は次のとおりです。

"Index#: 1, is checked. Checked state is:984"  
"Index#: 2, is checked. Checked state is:984"  
"Index#: 3, is checked. Checked state is:984" 

助けてくれてありがとう!

4

4 に答える 4

1

これを試して:

foreach (int indexChecked in chkListCustomer.CheckedIndices)
{
    MessageBox.Show("Index#: " + indexChecked.ToString() +
        ", is checked. Checked state is:" +
        chkListCustomer.Items[indexChecked].ToString()  + ".");   
}
于 2011-07-19T18:58:15.503 に答える
1

実際にインデックスが必要ない場合はCheckedItemsプロパティを使用できます。

foreach (DataRowView checkedItem in chkListCustomer.CheckedItems)
{
    MessageBox.Show("Checked item: "
        + checkedItem[chkListCustomer.ValueMember].ToString()
        + ".");
}
于 2011-07-19T19:01:07.357 に答える
0

あなたは使用する必要があります

chkListCustomer.GetItemCheckState(indexChecked).ToString()

それ以外の

chkListCustomer.SelectedValue.ToString()

CheckedIndicesおよびCheckedListBoxクラスに関するMSDNの詳細情報。

.Itemsまた、プロパティを反復処理することもできます。

foreach(object itemChecked in chkListCustomer.CheckedItems) {
    // Use the IndexOf method to get the index of an item.
    MessageBox.Show("Item with title: \"" + itemChecked.ToString() + 
                    "\", is checked. Checked state is: " + 
        chkListCustomer.GetItemCheckState(chkListCustomer.Items.IndexOf(itemChecked)).ToString() + ".");
    MessageBox.Show(itemChecked.ToString())
}
于 2011-07-19T19:00:08.303 に答える
0

AhmadMageedからのこの投稿のSOで見つかったコードの一部を変更しました。これは私にそれぞれを与えます

    foreach (object itemChecked in chkListPatients.CheckedItems) 
    {
        DataRow row = (itemChecked as DataRowView).Row;
        string id = row[0].ToString();
        MessageBox.Show(id);
    }
于 2011-07-21T14:27:00.730 に答える