I have about 1000 rows in a DataGridView
. Want to implement a CheckBox
column for users to select single row. Current implementation is slow during the initial select. The loop is causing the problem:
dataGridView_1_CellContentClick(object sender, DataGridViewCellEventArgs e)
dataGridView_1.CommitEdit(DataGridViewDataErrorContexts.Commit);
private void dataGridView_1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView_1.Columns["Selected"].Index)
if (Convert.ToInt16(dataGridView_1.Rows[e.RowIndex].Cells[0].Value) == 1)
{
foreach (DataGridViewRow DR in dataGridView_PrimeMover.Rows)
{
if (DR.Index != e.RowIndex)
{
DR.Cells[0].Value = 0;
}
}
......
......
}
}
How to implement a lookalike RadioButton
column in the DataGridView
which can handle large data?
Try below:
I've changed the if case inside the foreach loop, you don't need to assign value to every row, see if it's faster
if (e.ColumnIndex == dataGridView_1.Columns["Selected"].Index)
if (Convert.ToInt16(dataGridView_1.Rows[e.RowIndex].Cells[0].Value) == 1)
{
foreach (DataGridViewRow DR in dataGridView_PrimeMover.Rows)
{
if((int)DR.Columns["Selected"] == 1 && DR.Index != e.RowIndex)
DR.Columns["Selected"] = 0;
}
}
So many DataGridView's events know me but I don't know them, hope this help.
int SelectedRowIndex;
private void InitDGVData()
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
DataColumn dc1 = new DataColumn();
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
for (int i = 0; i < 10000; i++)
{
dt.Rows.Add(i.ToString(), i.ToString());
}
dataGridView1.DataSource = dt;
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.Name = "Selected";
dataGridView1.Columns.Add(col);
SelectedRowIndex = dataGridView1.CurrentRow.Index;
dataGridView1.Rows[SelectedRowIndex].Cells[dataGridView1.Columns["Selected"].Index].Value = true;
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["Selected"].Index && e.RowIndex != SelectedRowIndex)
{
dataGridView1.Rows[SelectedRowIndex].Cells[dataGridView1.Columns["Selected"].Index].Value = false;
SelectedRowIndex = e.RowIndex;
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[SelectedRowIndex].Cells[dataGridView1.Columns["Selected"].Index].Value = true;
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["Selected"].Index && e.RowIndex == SelectedRowIndex)
e.Cancel = true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.