Goal
Currently looking to find a way how to select items from DataGridView and order it by the selected first at top.
Example
First selection by user:
Selected Column1 Column2
a 1
b 2
c 3
x d 4
Second selection...
Selected Column1 Column2
a 1
x b 2
c 3
x d 4
Third selection...
Selected Column1 Column2
x a 1
x b 2
c 3
x d 4
Order
4th row
2nd row
1st row
Summary
The 1st item selected by user was the 4th row, then the 2nd and lastly the 1st row.
Question
How can I get a list of the all rows in order as explained above?
Current Code
I created a checkbox column like so, so the user can see what they have selected.
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.Name = "Selected";
checkBoxColumn.HeaderText = "Selected";
checkBoxColumn.ReadOnly = false;
productsView.Columns.Add(checkBoxColumn);
User then checks the checkbox to mark the selected records they desire, then they click a button to which opens another form.
But the order is mixed.
private void addBtn_Click(object sender, EventArgs e)
{
foreach (var row in checkedRows)
{
DateTime dateTime = dateText.Value;
string orderNumber = orderNumberText.Text;
SelectedProducts form = new SelectedProducts(dateTime, orderNumber);
form.ShowDialog();
}
}
I think i would:
Create a new list that would store my data depending on the new order.
List<Item> SelectedItemList= new List<Item>
Listen to the checkbox column value change. Add to the "SelectedList" when checkbox is checked or remove it when unchecked.( How to detect DataGridView CheckBox event change?)
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
if ((bool)dataGridView1.SelectedRows[0].Cells[2].Value) //the index of checkbox column
SelectedItemList.Add(itemBindingSource.current as Item)//add data to the list
else
SelectedItemList.Remove(itemBindingSource.current as Item) // remove data to list
}
}
Then use the list as parameter to the form display.
SelectedProducts form = new SelectedProducts(SelectedItemList);
form.ShowDialog();
You don't need to track the selection by each check-change. Just get the checked rows when you need them:
var checkedRows = dataGridView1.SelectedRows.Cast<DataGridViewRow>()
.Where(r => (bool)r.Cells["Selected"].Value == true)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With