数据网格视图中的复选框不会更新我的bindingList

时间:2011-06-23 15:26:53

标签: c# visual-studio

我有一个包含2列的数据网格。一个是复选框,一个是普通文本框单元格。 All绑定到一个BindingList,它是一个实体。

如果我选中一个复选框然后循环以从BindingList获取已检查的实体,则它不返回任何内容。但是如果我检查然后编辑文本框列,它就可以正常工作并返回一个结果。

我尝试刷新或检查然后点击其他地方。它不起作用。

如何在检查列时设置更新bindingList?

谢谢!

1 个答案:

答案 0 :(得分:1)

数据源(dataTable)中的列是什么数据类型?它是布尔类型吗?

但这并不重要,重要的是你使用dgv的正确事件。 使用: 1. CurrentCellDirtyStateChanged和 2. CellValueChanged

这是您必须使用的代码:

    private void CreateAndBind()
    {
        DataTable table = GetDataToDataTable();
        //then bind it to dgv:
        dgv.DataSource = new BindingSource(table, null);
        //create events for dgv:
        dgv.CurrentCellDirtyStateChanged += new EventHandler(dgv_CurrentCellDirtyStateChanged);
        dgv.CellValueChanged += new EventHandler(dgv_CellValueChanged);
    }

    private DataTable GetDataToDataTable()
    {
        //get data from dataBase, or what ever...   
        table.Columns.Add("column1", typeof(stirng));
        table.Columns.Add("column2", typeof(bool));

        //adding some exmaple rows:
        table.Rows.Add("item 1", true);
        table.Rows.Add("item 2", false);
        return table;
    }

    void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

    private void dgv_CellValueChanged(object obj, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0) //compare to checkBox column index
        {
            DataGridViewCheckBoxCell check = dataGridView1[0, e.RowIndex] as DataGridViewCheckBoxCell;
            if (Convert.ToBoolean(check.Value) == true)
            {
                //If tick is added!
                //
            }
        }
    }

希望它有所帮助。