DataGridView checkbox column - value and functionality

后端 未结 11 1764
一向
一向 2020-11-28 12:17

I\'ve added a checkbox column to a DataGridView in my C# form. The function needs to be dynamic - you select a customer and that brings up all of their items that could be s

11条回答
  •  天涯浪人
    2020-11-28 12:47

    it took me a long time to figure out how to do this without having to loop through all the records. I have a bound datagridview-source, and all fields are bound except for the checkbox-column. So I don't have/need a loop to add each row and I didn't want to create one just for this purpuse. So after a lot of trying I finally got it. And it's actually very simple too:

    First you add a new .cs File to your project with a custom-checkbox cell, e.g.

    DataGridViewCheckboxCellFilter.cs:

    using System.Windows.Forms;
    
    namespace MyNamespace {
        public class DataGridViewCheckboxCellFilter : DataGridViewCheckBoxCell {
            public DataGridViewCheckboxCellFilter() : base() {
                this.FalseValue = 0;
                this.TrueValue = 1;
                this.Value = TrueValue;
            }
        }
    }
    

    After this, on your GridView, where you add the checkbox-column, you do:

    // add checkboxes
    DataGridViewCheckBoxColumn col_chkbox = new DataGridViewCheckBoxColumn();
    {
        col_chkbox.HeaderText = "X";
        col_chkbox.Name = "checked";
        col_chkbox.CellTemplate = new DataGridViewCheckboxCellFilter();                
    }
    this.Columns.Add(col_chkbox);
    

    And that's it! Everytime your checkboxes get added in a new row, they'll be set to true. Enjoy!

提交回复
热议问题