c#从调查表样式DataGridView的多个复选框列中仅选择一个复选框

问题描述 投票:2回答:2

我已经创建了一个显示带有一系列问题的datagridview的应用程序。dgv结构由一个用于问题文本的字符串列和三个用于答案的布尔/复选框列组成(是,否,不适用)。每个问题都显示在其自己的行上。

我希望我的程序仅允许用户在每一行上选择是,仅否或不适用。

我认为当一个选项被选中但我不太确定如何执行此操作时,我需要取消选中其他复选框选项。

我已经设置了CellValueChanged和CellContentClick事件,但是我不确定代码是否需要实现所需的功能。

任何帮助表示赞赏。谢谢。

我到目前为止的代码:

private void dgvQuestions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int columnIndex = e.ColumnIndex;
            int rowIndex = e.RowIndex;

            DataGridViewCheckBoxCell chkYes = dgvQuestions.Rows[rowIndex].Cells[2] as DataGridViewCheckBoxCell;
            DataGridViewCheckBoxCell chkNo = dgvQuestions.Rows[rowIndex].Cells[3] as DataGridViewCheckBoxCell;
            DataGridViewCheckBoxCell chkNA = dgvQuestions.Rows[rowIndex].Cells[4] as DataGridViewCheckBoxCell;


            if (Convert.ToBoolean(chkYes.Value) == true)
            {

            }

            if (Convert.ToBoolean(chkNo.Value) == true)
            {

            }

            if (Convert.ToBoolean(chkNA.Value) == true)
            {

            }
        }

        private void dgvQuestions_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvQuestions.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
c# .net winforms datagridview datagridviewcolumn
2个回答
0
投票

this video是否显示您想要的行为?对我有用的是使用BindingList作为DataGridView的数据源。然后,使用复选框更改时发生的“ CellDirty”事件,可以使它们像单选按钮一样工作。

这是一个代表调查表的一个订单项的类的示例:

class QuestionaireItem
{
    public string Question { get; internal set; } = "Question " + _count++;
    public bool Yes { get; set; }
    public bool No { get; set; }
    public bool Maybe { get; set; } // OOPS! I should have said "NA"

    static int _count = 1;
}

当主窗体获得其Handle之前(在此之前将不起作用),我们初始化dataGridView1。我已添加评论以解释发生了什么:

protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    if (!DesignMode)    // We only want this behavior at runtime
    {
        // Create the binding list
        BindingList<QuestionaireItem> testdata = new BindingList<QuestionaireItem>();
        // And add 5 example items to it
        for (int i = 0; i < 5; i++) testdata.Add(new QuestionaireItem());
        // Now make this list the DataSource of the DGV.
        dataGridView1.DataSource = testdata;

        // This just formats the column widths a little bit
        dataGridView1.Columns["Question"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView1.Columns["Maybe"].Width =
        dataGridView1.Columns["Yes"].Width =
        dataGridView1.Columns["No"].Width = 40;

        // And this subscribes to the event (one of them anyway...)
        // that will fire when the checkbox is changed
        dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
    }
}

这里是处理CellDirty事件的方法,以使三个复选框(我分别将它们命名为Yes,No和Maybe)的作用类似于单选按钮:

private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    // The cell will be considered "dirty" or modified so Commit first.
    dataGridView1.EndEdit(DataGridViewDataErrorContexts.Commit);
    // Get the QuestionaireItem that is bound to the row
    QuestionaireItem item = (QuestionaireItem)
        dataGridView1
        .Rows[dataGridView1.CurrentCell.RowIndex]
        .DataBoundItem;
    // Now see which column changed:
    switch (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name)
    {
        case "Yes":
            item.No = false;        // i.e. "unchecked"
            item.Maybe = false;
            break;
        case "No":
            item.Yes = false;       
            item.Maybe = false;
            break;
        case "Maybe":
            item.Yes = false;
            item.No = false;
            break;
    }
    dataGridView1.Refresh();    // Update the binding list to the display
}

Clone or Download此示例来自GitHub。


0
投票

[您似乎已经正确设置了CellContentClick,但是,如果网格中还有其他列,那么,如果要检查以确保单击了其内容的单元格实际上是检查之一,则可能会很有用。盒单元格。否则,代码可能会不必要地设置单元格的值。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
  string colName = dataGridView1.Columns[e.ColumnIndex].Name;
  if (colName == "Yes" || colName == "No" || colName == "N/A") { 
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
  }
}

CellValueChanged事件中,代码再次应仅检查复选框值。另外,我假设必须检查至少一(1)个单元格。例如,如果最初选中“ N / A”单元格,则用户“取消选中”该单元格,则该行将没有选中“ NO”复选框。这是代码中的最后检查,如果用户“取消选中”“ N / A”单元格,而所有复选框都保持“未选中”,则代码将“选中”“ N / A”单元格。同样,重要的是在我们更改CellValueChanged事件中的任何复选框值之前“关闭” CellValueChanged事件,以避免重入。有点像...

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.RowIndex >= 0 && e.ColumnIndex >= 0) {
    string colName = dataGridView1.Columns[e.ColumnIndex].Name;
    bool checkValue;
    dataGridView1.CellValueChanged -= new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
    switch (colName) {
      case "Yes":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "No":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["No"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "N/A":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
        }
        else {
          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value == false &&
              (bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value == false) {
            dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
          }
        }
        break;
      default:
        break;
    }
    dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
  }

下面是一个简单的示例,其中包含三列“是”,“否”和“不适用”复选框。

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dataGridView1.DataSource = GetTable();
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Yes", typeof(bool));
  dt.Columns.Add("No", typeof(bool));
  dt.Columns.Add("N/A", typeof(bool));
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add(false, false, true);
  }
  return dt;
}

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.