在DataGridView中,在添加新行时将列的ReadOnly属性设置为false,以更新其true(c#.net)

时间:2011-10-19 16:38:11

标签: c# .net datagridview datatable readonly

我已将2个数据表列的readonly属性设置为true。

    List.Columns[0].ReadOnly = true;
    List.Columns[1].ReadOnly = true;

但我只希望它们只在用户尝试更新时才能读取,用户可以向dataGridView添加新行,所以我想在尝试添加新行时将readonly属性设置为false。我尝试在datagrid的CellDoubleClick事件上执行此操作,但它不会执行任何操作,因为它是为了调用beginedit而迟到。

if(e.RowIndex == GridView.Rows.Count-1)
                GridView.Rows[e.RowIndex].Cells[1].ReadOnly = GridView.Rows[e.RowIndex].Cells[0].ReadOnly = false;
            else
                GridView.Rows[e.RowIndex].Cells[1].ReadOnly = GridView.Rows[e.RowIndex].Cells[0].ReadOnly = true;

任何想法

2 个答案:

答案 0 :(得分:5)

您必须使用cellbegin编辑才能将单元格readonly属性设置为true。

   private  void dataGridView1_CellBeginEdit(object sender,DataGridViewCellCancelEventArgs e)
   {
       if (dataGridView1.Columns[e.ColumnIndex].Name == "ColName0")
       {
           // you can check whether the read only property of that cell is false or not

       }
   }

我希望它会帮助你...

答案 1 :(得分:2)

听起来你想做的就是将网格中的所有行都只读取,除非它们是新行,因此意味着创建的行无法编辑。如果这是正确的那么你可以做的是在DataBindingComplete事件期间将行设置为readonly,如下所示:

dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
        if (!item.IsNewRow)
            item.ReadOnly = true; 
    }
}

重要的是检查行是否是新行。

相关问题