none
How to use unbound checkbox RRS feed

  • Question

  • Hi all ,

    I have a DatagridView with some data and i have a function to loop on selected rows using (foreach ....... MyDGV.SelectedRows) to achieve some functions, so to do that i have to manually while pressing ctrl button select  my rows but if i tried as you know that without pressing ctrl all previous selected will be released and here is my help need point

    i want to add unbound checkbox field to my datagridview this field function is just for selecting rows in no need to keep ctrl button pressing , so just set checkbox to checked state and the specific row should be selected or not selected when the Checkbow state is become unchecked ,so this is my request.

    Thanks


    Esmat

    Friday, October 11, 2019 6:36 PM

All replies

  • Hi Esmat_Halfa,

    Thank you for posting here.

    According to your description, you want to use checkbox to select some rows.

    You could try the following code to get it.

    public partial class Form1 : Form
        {
            private DataTable dt;
            public Form1()
            {
                InitializeComponent();
                DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
                CheckboxColumn.TrueValue = true;
                CheckboxColumn.HeaderText = "Select";
                CheckboxColumn.FalseValue = false;
                CheckboxColumn.Width = 50;
                dataGridView1.Columns.Add(CheckboxColumn);
            }
           
            private void Form1_Load(object sender, EventArgs e)
            {
                string constring = @"connString";
                SqlConnection con = new SqlConnection(constring);
                con.Open();
                string sql = "select * from Stu";
    
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
                DataSet set = new DataSet();
                dataAdapter.Fill(set);
                dataGridView1.DataSource = set.Tables[0].DefaultView;
                dt = set.Tables[0];
            }
    
            private void Button1_Click(object sender, EventArgs e)
            {
                int count = 0;
    
                DataTable dt2 = dt.Clone();
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True") 
                    {
                        count++;
                        DataRow row = dt.Rows[i];
                        dt2.ImportRow(row);
                    }
                }
                if (count == 0)
               {
                    MessageBox.Show("Please select at least one row.", "Tip");
                    return;
                }
                else
                {
                    dataGridView2.DataSource = dt2;
                }
            }
    }

    If it still exists the problem, please feel free to let us know.

    Result:

    Best regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, October 14, 2019 5:07 AM
  • Hello,

    The following is with a SQL-Server database. The SELECT creates a non existing field set to false along with fields in the table.

    Using the following method to get data into a DataTable, note the Process field is read-only so it's set not to be read-only below.

    public DataTable GetCustomers()
    {
        var dt = new DataTable();
    	using (var cn = new SqlConnection {ConnectionString = ConnectionString})
    	{
    	    using (var cmd = new SqlCommand() {Connection = cn})
    	    {
    	        cmd.CommandText = "SELECT CONVERT(BIT,0) AS Process," + 
    	                              "Identifier," + 
    	                              "CompanyName," + 
    	                              "ContactName " + 
    	                          "FROM dbo.Customer";
                cn.Open();
                dt.Load(cmd.ExecuteReader());
    	        dt.Columns["Process"].ReadOnly = false;
    	    }
    	}
    
    	return dt;
    }

    In the form, a BindingSource component is used which provides an easy way to work with data (if you have not used them before check them out as they are worth using).

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Windows.Forms;
    using DataOperations; // this is where GetCustomers is
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            private readonly BackendOperations _dataOperations = new BackendOperations();
            private readonly BindingSource _bsCustomers = new BindingSource();
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                _bsCustomers.DataSource = _dataOperations.GetCustomers();
                dataGridView1.DataSource = _bsCustomers;
                dataGridView1.Columns["Identifier"].Visible = false;
            }
            /// <summary>
            /// Get checked rows
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void GetCheckedButton_Click(object sender, EventArgs e)
            {
                List<DataRow> result = ((DataTable) _bsCustomers.DataSource)
                    .AsEnumerable()
                    .Where(row => row.Field<bool>("Process"))
                    .ToList();
    
                if (result.Count <= 0) return;
                {
                    foreach (var row in result)
                    {
                        Console.WriteLine(row.Field<int>("Identifier"));
                    }
                }
            }
        }
    }
    

    Note if you want the check column in a different location that can be done too.

    Note that the header text can be polished up too.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, October 14, 2019 10:17 AM
    Moderator