不解释整个上下文,我的问题基本上是这样的:
我在绑定(bind)到 Entity Framework DbSet 的 Windows 窗体上有一个数据 GridView :dbSet<TEntity>.Local.ToBindingList()
.
如果我设置 datagridview 的 ReadOnly
属性设置为 true(在设计 View 中),然后在我的代码中包含以下语句:
myDataGridView.Rows[rowIndex].ReadOnly = false;
它在不改变值的情况下直接通过! (不,我的数据源不是只读的。)
遍历行中的单元格并单独设置每个单元格的 ReadOnly 属性也不起作用:
foreach (DataGridViewCell cell in myDataGridView.Rows[rowIndex].Cells)
{
cell.ReadOnly = false;
}
.ReadOnly - Gets or sets a value indicating whether the user can edit the cells of the DataGridView control.
但由于某种原因,它表现得好像无法设置。
是否有发生这种情况的原因?我在想也许 datagridview 的 ReadOnly
属性将覆盖对特定行/单元格所做的任何更改(即 整个表单 必须是只读的或不是),但显然 this为某人工作...
还有其他方法可以实现我的最终目标,但我想知道为什么我不能更改此属性,因为这对于我的情况来说是最简单的解决方案。
编辑:
让我试着澄清一下我的问题:
同样,我知道还有其他方法可以实现我的最终目标,但我想知道这个问题的答案:
对于原始示例很抱歉,但要轻松重现该问题,请创建一个 WinForm 应用程序,在其上放置一个数据 GridView ,然后将此代码传递到您的项目中:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ReadOnly = true;
string[] row1 = new string[] { "test", "test1" };
string[] row2 = new string[] { "test2", "test3" };
string[] row3 = new string[] { "test4", "test5" };
dataGridView1.Columns.Add("1", "1");
dataGridView1.Columns.Add("2", "2");
dataGridView1.Rows.Add(row1);
dataGridView1.Rows.Add(row2);
dataGridView1.Rows.Add(row3);
dataGridView1.Rows[1].ReadOnly = false;
}
}
如果您在最后一行放置一个断点,然后单步执行它,您将看到 ReadOnly 属性没有改变!为什么??
最佳答案
所以我已经为我的问题找到了解决方案/解决方法,尽管我仍然不确定为什么...
显然,如果您想逐行更改 DataGridView 的 ReadOnly 属性,您不能设置main DataGridView.ReadOnly 属性,因为显然这会覆盖任何后续变化。
要重用我之前的示例,解决方法是遍历行并设置每个ROW 的 ReadOnly 属性(与设置datagridview 的 ReadOnly 属性相反),然后您可以单独更改每行的 ReadOnly 属性:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//dataGridView1.ReadOnly = true;
string[] row1 = new string[] { "test", "test1" };
string[] row2 = new string[] { "test2", "test3" };
string[] row3 = new string[] { "test4", "test5" };
dataGridView1.Columns.Add("1", "1");
dataGridView1.Columns.Add("2", "2");
dataGridView1.Rows.Add(row1);
dataGridView1.Rows.Add(row2);
dataGridView1.Rows.Add(row3);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.ReadOnly = true;
}
dataGridView1.Rows[1].ReadOnly = false;
}
}
这对我来说非常有用,但是对于为什么我的原始问题中的代码无法正常工作的任何见解都将不胜感激!
关于c# - 以编程方式更改 DataGridView 行上的只读模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13996412/