Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

c# - DataGridView checkbox column - value and functionality

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 serviced, and you select which of them you wish to be serviced this time around.

Anyway, the code will now add a chckbox to the beginning of the DGV. What I need to know is the following:

1) How do I make it so that the whole column is "checked" by default? 2) How can I make sure I'm only getting values from the "checked" rows when I click on a button just below the DGV?

Here's the code to get the column inserted:

DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
            doWork.HeaderText = "Include Dog";
            doWork.FalseValue = "0";
            doWork.TrueValue = "1";
            dataGridView1.Columns.Insert(0, doWork);

So what next? Any help would be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this:

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        row.Cells[CheckBoxColumn1.Name].Value = true;
    }
    
  2. The Click event might look something like this:

    private void button1_Click(object sender, EventArgs e)
    {
        List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
            {
                rows_with_checked_column.Add(row);
            }
        }
        // Do what you want with the check rows
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...