1

Good ol' Ellie here with an Visual Studio 2010 question。

我在数据网格视图中有一个列,它只是一个复选框,我希望它显示为选中状态,除非用户特别取消选中它。我发现的唯一事情是如何检查它是否只是一个独立的复选框。

提前感谢您的帮助!

艾莉

4

3 回答 3

2

循环遍历每一行并选中其各自的框,使其显示为选中(默认情况下)。

应该是这样的:

foreach (DataGridViewRow row in dataGridView.Rows)     
{
    row.Cells[CheckBoxColumn.Name].Value = true;     
} 
于 2012-05-22T19:22:29.827 回答
0

如果要将 DataGridView 绑定到集合,则可以将对象的布尔属性的默认值设置为 true,将对象添加到 BindingList 集合,并将集合设置为 DataGridView 的数据源。

例如,要绑定到 DataGridView 的集合将包含所需的属性(每个属性代表一个列),包括一个表示复选框列的布尔属性。这是该类的外观示例:

public class Product : INotifyPropertyChanged
{
    private bool _selected;
    private string _product;

    public event PropertyChangedEventHandler PropertyChanged;

    public Product(string product)
    {
        _selected = true;
        _product = product;
    }

    public bool Selected
    {
        get { return _selected; }
        set
        {
            _selected = value;
            this.NotifyPropertyChanged("Selected");
        }
    }

    public string ProductName
    {
        get { return _product; }
        set
        {
            _product = value;
            this.NotifyPropertyChanged("Product");
        }
    }


    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

在包含 DataGridView 的表单中,您可以将项目添加到 BindingList 并将该集合绑定到 DataGridView:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        InitGrid();
    }

    private void InitGrid()
    {
        dgProducts.AutoGenerateColumns = true;

        BindingList<Product> products = new BindingList<Product>();

        products.Add(new Product("Eggs"));
        products.Add(new Product("Milk"));
        products.Add(new Product("Bread"));
        products.Add(new Product("Butter"));

        dgProducts.DataSource = products;
    }

}

这只是一个快速而肮脏的示例,但展示了如何为对象设置默认值,将该对象添加到 BindingList,然后将其添加到 DataGridView。

要在绑定列表后添加项目,您始终可以访问 DataSource 集合并添加到它(下面的示例代码假设一个按钮被添加到表单并连接到下面显示的单击事件,以及一个名为 newItemName 的文本框):

    private void addItemButton_Click(object sender, EventArgs e)
    {
        BindingList<Product> products = dgProducts.DataSource as BindingList<Product>;
        products.Add(new Product(newItemName.Text));
    }
于 2012-05-22T19:56:00.240 回答
0

我现在有同样的问题。
我的解决方案是,在我的 dataGridView 上使用一个事件。
您只需获取当前行并将复选框列的空值替换为 true 或 false。

    private void myDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        // Get current row.
        DataGridViewRow obj = myDataGridView.CurrentRow;
        // Get the cell with the checkbox.
        DataGridViewCheckBoxCell oCell = obj.Cells[theIndexOfTheCheckboxColumn] as DataGridViewCheckBoxCell;
        // Check the value for null.
        if (oCell.Value.ToString().Equals(string.Empty))
            oCell.Value = true;
    }
于 2017-07-12T13:43:20.250 回答