datagridview复选框列为单个选定行的单选按钮

时间:2015-07-15 02:52:25

标签: c# .net winforms datagridview

我在DataGridView中有大约1000行。 想要为用户实施CheckBox列以选择单行。 在初始选择期间,当前实现很慢。循环导致问题:

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;
            }
        }
    ......
    ......
   }
}

如何在RadioButton中实现可以处理大数据的类似DataGridView列?

2 个答案:

答案 0 :(得分:0)

尝试以下:

我已经改变了foreach循环中的if case,你不需要为每一行赋值,看看它是否更快

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;
        }
   }

答案 1 :(得分:0)

许多DataGridView的事件都知道我,但我不了解它们,希望这有帮助。

    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;
    }