C# 如何允许以编程方式编辑数据网格视图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9534465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to allow editing of a datagridview programmatically?
提问by HMcompfreak
I have a datagridview connected to a database. I have a checkbox for enabling the data to be edited in datagridview. If the checkbox is checked then only 1 column of datagridview can be edited, and after editing click on save button to reflect it in database and when checkbox is unchecked editing is disabled.
我有一个连接到数据库的数据网格视图。我有一个复选框,用于在 datagridview 中编辑数据。如果选中该复选框,则只能编辑 datagridview 的 1 列,编辑后单击保存按钮将其反映在数据库中,未选中复选框时禁用编辑。
I've tried something like this:
我试过这样的事情:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.CheckState == CheckState.Checked)
{
dataGridView1.CurrentRow.ReadOnly = false;
dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
}
else if (checkBox1.CheckState == CheckState.Unchecked)
{
dataGridView1.ReadOnly = true;
}
}
This code misses the concept of selecting the columns to be edited.
此代码忽略了选择要编辑的列的概念。
回答by Lukinha RS
To do what you want, you must to set only a column that you want to disabled.
要执行您想要的操作,您必须仅设置要禁用的列。
dataGridView1.Columns[0].ReadOnly = true;
dataGridView1.Columns[1].ReadOnly = false;
But, do you want to do this? Block an entire column?
但是,你想这样做吗?阻止整个列?
回答by ThunderGr
You can try
你可以试试
if(dataGridView1.SelectedCells.Count>0) dataGridView1.SelectedCells[0].ReadOnly=false;
instead of
代替
dataGridView1.CurrentRow.ReadOnly=false;
回答by ahmed mohamady
for (int i = 0; i <= dataGridView1.ColumnCount - 1; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
回答by Stanley Gillmer
The help provided in this section can only work if your datagridview's own readonly property is set to false. if it isn't the read only property of each column will persist. When you use the smart tag to choose and enable "make grid editable" then the readonly property is set to false. also what's nice in the new generation grid is that you don't have to find the column like in
本节提供的帮助仅在您的 datagridview 自己的 readonly 属性设置为 false 时才有效。如果它不是每列的只读属性将持续存在。当您使用智能标记选择并启用“使网格可编辑”时,只读属性设置为 false。新一代网格中还有一个好处是你不必像这样找到列
foreach (var col in grid1.columns)
you can just use the name of the column as chosen or as default "column1.ReadOnly = false". the enumerator has it's own advantages of course.
您可以仅使用所选列的名称或作为默认“column1.ReadOnly = false”。枚举器当然有它自己的优势。

