winforms 在DataGridView C#中禁用复选框单元格

4xrmg8kj  于 11个月前  发布在  C#
关注(0)|答案(1)|浏览(130)

我有一个C#表单,其中有一个dataGridView。在dataGridView中,我有一些列的字符串文本是来自数据库。我有两个有复选框的其他列。我想让这些行读-只根据某些条件.我试图使整行只读只影响文本列,而不是复选框列.我想禁用复选框列,使他们不能编辑(它们应保持固定状态)。
到目前为止,我已经尝试过了,我有一个列表(disabledRow),其中包含需要禁用的行的值

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // Check if the cell value in the first column matches any value in the list
    if (disabledRows.Contains(row.Cells[0].Value?.ToString()))
    {
        // Set the entire row to ReadOnly
        row.ReadOnly = true;
        

    }
}

字符串

sgtfey8w

sgtfey8w1#

如果我根据你的需求创建了我的示例演示,我就能得到你想要的行为。

public partial class Form1 : Form
{
    public class SampleData
    {
        public string StringData { get; set; }
        public bool Checkbox1Data { get; set; }
        public bool Checkbox2Data { get; set; }
    }
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataGridView dataGridView = new DataGridView();
        dataGridView.Dock = DockStyle.Fill;
        dataGridView.AutoGenerateColumns = false;

        // Create a string column
        DataGridViewTextBoxColumn stringColumn = new DataGridViewTextBoxColumn
        {
            HeaderText = "String Column",
            DataPropertyName = "StringData",
        };
        dataGridView.Columns.Add(stringColumn);

        // Create a checkbox column 1
        DataGridViewCheckBoxColumn checkBoxColumn1 = new DataGridViewCheckBoxColumn
        {
            HeaderText = "Checkbox 1",
            DataPropertyName = "Checkbox1Data",
        };
        dataGridView.Columns.Add(checkBoxColumn1);

        // Create a checkbox column 2
        DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn
        {
            HeaderText = "Checkbox 2",
            DataPropertyName = "Checkbox2Data",
        };
        dataGridView.Columns.Add(checkBoxColumn2);

        // Create a data source with sample data
        var dataSource = new BindingList<SampleData>
        {
            new SampleData { StringData = "Row 1", Checkbox1Data = false, Checkbox2Data = true },
            new SampleData { StringData = "Row 2", Checkbox1Data = true, Checkbox2Data = false },
            new SampleData { StringData = "Row 3", Checkbox1Data = false, Checkbox2Data = false }
        };

        dataGridView.DataSource = dataSource;

        // Add the DataGridView to the form
        Controls.Add(dataGridView);

        List<string> strings = new List<string>();
        strings.Add("Row 1");
        strings.Add("Row 2");

        foreach (DataGridViewRow row in dataGridView.Rows) 
        {
            if (strings.Contains(row.Cells[0].Value)) 
            {
                MessageBox.Show(row.ReadOnly.ToString());
                row.ReadOnly = true;
                MessageBox.Show(row.ReadOnly.ToString());
            }
        }
        dataGridView.Refresh();
}
}

字符串

相关问题