In DataGridView turn ReadOnly property of column to false when adding new row, on updating its true (c#.net)

最后都变了- 提交于 2020-01-04 06:22:36

问题


I have set the readonly property of 2 datatable columns to true.

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

But i only want them to be read only when user is trying to update, User can add new rows to dataGridView so i want to turn the readonly property to false when trying to add new row. i tried doing this on CellDoubleClick event of the datagrid but it wont do anything as it is to late for the beginedit to be called.

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;

Any ideas


回答1:


you Have to use the cellbegin edit to make the cell readonly property to 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

       }
   }

I hope it will helps you...




回答2:


It sounds like what you want to do is make all the rows in the grid readonly unless they are the new row, thus meaning created rows cannot be edited. If that is correct then what you can do is set the row to readonly during the DataBindingComplete event like so:

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; 
    }
}

The important part is the check to see if the row is the new row.



来源:https://stackoverflow.com/questions/7824813/in-datagridview-turn-readonly-property-of-column-to-false-when-adding-new-row-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!