Reputation: 1
Want to show price of a selected in datagridview into a lablel. For now am using a loop to show the price but it only give me the first selected price only.
Code to show price
int selectedCellCount = dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
for (int i = 0; i < selectedCellCount; i++)
{
int row = dataGridView1.SelectedCells[i].RowIndex;
label3.Text = dataGridView1.Rows[row].Cells[3].Value.ToString();
}
}
Also how can i calculate total price for entered quantity
Upvotes: 0
Views: 261
Reputation: 1
This is the Answer. Thanks everybody
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) // make sure user select at least 1 row
{
label3.Text = dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
}
Upvotes: 0
Reputation: 546
I think that I got your point from your comment on one of the answer. You want that whenever you select row, price of the selected row show in label ? Right.
For this you can use DataGridView Event named SelectionChanged(), so whenever your selection changed, this event triggers and change your label.
Assuming your gridview allows only one selection.
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
label.Text = row.Cells[3].Value.ToString();
}
Hope this helps you.
Upvotes: 1
Reputation: 572
Try this
List<int> indexes = dataGridView1.SelectedRows.Cast<DataGridViewRow>().Select(x => Select(x => x.Index).ToList();
int sum = 0;
for (int i = 0; i < indexes.Count; i++)
{
// here the label text will be the last row price because you overwrite each time
label3.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
sum += int.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString());
}
MessageBox.Show("Sum of selected rows = " + sum.ToString());
Upvotes: 0