How do I allow edit only a particular column in datagridview in windows application?

人盡茶涼 提交于 2019-12-28 12:15:25

问题


I want to enable only two columns in the DataGridview to be able to edit. The others should not be allowed to edit. Further I am not directly linking to datasource; I will be doing some thing like this way

DataTable dt = new DataTable();
dt.Columns.Add("Email");
dt.Columns.Add("email1");
for (int i = 0; i < 5; i++)
{
    DataRow dr = dt.NewRow();
    dr["Email"] = i.ToString();
    dr["email1"] = i.ToString() + "sdf";
    dt.Rows.Add(dr);
}
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;

So which property should I set, that will enable only one column say Email(in the above eg) to be editable.


回答1:


Set the ReadOnly property of the other columns to true.

(You'll probably need to loop through the Columns collection and use an if statement)




回答2:


dataGridView1.ReadOnly = false;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[2].ReadOnly = true;

here first column (index 0) will be editable.




回答3:


foreach (DataGridViewColumn dc in dataGridViewX1.Columns)
{
       if (dc.Index.Equals(0) || dc.Index.Equals(1))
       {
           dc.ReadOnly = false;
       }
       else
       {
            dc.ReadOnly = true;
       }
 }


来源:https://stackoverflow.com/questions/2597268/how-do-i-allow-edit-only-a-particular-column-in-datagridview-in-windows-applicat

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