C# DataGridView Read Only Columns and Rows

The DataGridView control, along with its interconnected classes, has been carefully crafted to offer a remarkably adaptable and extensible system dedicated to the presentation and manipulation of tabular data. Its design philosophy centers around flexibility, ensuring that developers have the freedom to tailor the control to their specific requirements.

Read Only Columns and Rows

One essential aspect of data manipulation within the DataGridView is the ReadOnly property. This crucial attribute determines whether the cell's displayed data can be edited or remains static.

dataGridView1.ReadOnly = true; dataGridView1.Rows[index].ReadOnly = true; dataGridView1.Columns[index].ReadOnly = true;

The ReadOnly property can be set at three distinct levels, granting a high degree of versatility. Firstly, developers have the option to designate the entire DataGridView as ReadOnly, effectively preventing any modifications to the data displayed within the control as a whole. Secondly, the ReadOnly property can be set at the column level, allowing developers to selectively restrict editing for specific columns, while still permitting modifications in other areas. Lastly, developers can set the ReadOnly property at the row level, empowering them to designate entire rows as read-only, limiting modifications to those specific rows while preserving the editability of the remaining data.

The following C# source code shows how to make a row as Readonly in a DataGridView.

Full Source C#
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { dataGridView1.ColumnCount = 3; dataGridView1.Columns[0].Name = "Product ID"; dataGridView1.Columns[1].Name = "Product Name"; dataGridView1.Columns[2].Name = "Product Price"; string[] row = new string[] { "1", "Product 1", "1000" }; dataGridView1.Rows.Add(row); row = new string[] { "2", "Product 2", "2000" }; dataGridView1.Rows.Add(row); row = new string[] { "3", "Product 3", "3000" }; dataGridView1.Rows.Add(row); row = new string[] { "4", "Product 4", "4000" }; dataGridView1.Rows.Add(row); dataGridView1.Rows[1].ReadOnly = true; } } }

Conclusion

Exploiting the flexible nature of the DataGridView's ReadOnly property, developers can precisely manage the editability of data within their applications, striking the ideal balance between data integrity and user interactivity.