C# 如何使datagridview的单个单元格只读?

C# 如何使datagridview的单个单元格只读?,c#,winforms,datagridview,datagridviewcolumn,C#,Winforms,Datagridview,Datagridviewcolumn,我的winform中有一个DataGridView。我想在特定条件下使此datagridview的单个单元格不可编辑。为此,我尝试了两种方法,但其中任何一种都不适合我。 这是密码 private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { foreach (DataGridViewRow row in dataGridView1.Rows) {

我的winform中有一个DataGridView。我想在特定条件下使此datagridview的单个单元格不可编辑。为此,我尝试了两种方法,但其中任何一种都不适合我。 这是密码

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            try
            {
                if (row.Cells[4].Value.ToString() == "0")
                {
                    row.Cells[2].ReadOnly = true;
                    row.Cells[2].Value = "0";
                }
                else
                {

                }
            }
            catch (Exception ee)
            {

            }
        }
        //if (dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString() == "0")
        //{
        //    dataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = true;
        //    dataGridView1.Rows[e.RowIndex].Cells[2].Value = "0";
        //}
    }
foreach循环中的代码引发一个异常,即对象引用未设置为对象的实例。 代码的注释部分将“所有单元格只读”属性设置为true。但是我想要的是,只有那些单元格属性设置为true,其中单元格[4].value=0
请告诉我应该怎么做才能根据条件更好地工作。

所以它会抛出一个异常-哪个对象引用为null?单元格[4]是否具有可转换为字符串的值?您是否尝试过调试和单步执行它引发错误的位置?单元格[4]具有来自数据库的值0@马什顿是的!!单元格[4]出现异常。值不是零@Pavenhimself如果不在行中,它什么时候抛出错误。单元格[4]。Value.ToString==0?