0

I have a table with two checkBoxes and I want to uncheck one of it while the other one is checked (like RadioButton).

enter image description here

void DataGridView1CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewCheckBoxCell never = dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewCheckBoxCell;
        DataGridViewCheckBoxCell once = dataGridView1.Rows[e.RowIndex].Cells[2] as DataGridViewCheckBoxCell;

        bool isNeverChecked = (bool)never.EditedFormattedValue;

        if(isNeverChecked){
            once.Value = "false";
            never.Value = "true";
        }else{
            once.Value = "true";
            never.Value = "false";
        }
        dataGridView1.Refresh();
    }
Little Fox
  • 1,212
  • 13
  • 39

2 Answers2

0
if(checkbox1.isChecked)
 checkbox2.isChecked = false;

the same with the checkbox2...

But you should wire this to the checkbox event is checked.

Also if you are using wpf, you can use binding I suppose

Alexander
  • 405
  • 7
  • 17
0

with something like this dgv.Rows[0].Cells[0].Value = true;

using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataGridView dgv = new DataGridView();

        public Form1()
        {
            InitializeComponent();
            initours();

            checkone();
        }

        private void checkone()
        {
            dgv.Rows[0].Cells[0].Value = true;//chekc the one in the first row
        }

        private void initours()
        {
            this.Controls.Add(dgv);
            dgv.Dock = DockStyle.Fill;

            dgv.AutoGenerateColumns = false;
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            dgv.Columns.Add(col);
            dgv.Rows.Add();
            dgv.Rows.Add();
            dgv.Rows.Add();
            dgv.Rows.Add();
        }
    }
}

Or using a datasource as suggested by others.

using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        DataGridView dgv = new DataGridView();
        BindingList<dgvitem> dgvdata = new BindingList<dgvitem>();
        public Form2()
        {
            InitializeComponent();
            initours();


            //add data
            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add(new dgvitem { checkcol = false, col2 = $"col2 row {i}" });
            }


            //check one of them
            dgvdata[2].checkcol = true;

        }

        private void initours()
        {
            this.Controls.Add(dgv);
            dgv.Dock = DockStyle.Fill;
            dgv.DataSource = dgvdata;
        }
    }



    public class dgvitem
    {
        public bool checkcol { get; set; }
        public string col2 { get; set; }
    }
}
blaze_125
  • 2,262
  • 1
  • 9
  • 19