我有一个 datagridview,它从 db 加载信息。但是,在运行时,我想允许用户更新一个单元格(默认情况下是只读的)但我不能这样做,我需要这样做,因为所有更改都保存在 db 中但是如果我重新加载它它,一些颜色样式等将消失,因此我只想根据请求从 db 重新加载并更改只读 col 的文本,请指导。
谢谢
这是 Question
用户的实际情况
我在 datagridview 中有一个列,默认情况下(I dont set it readonly anywhere in code
)是只读的。它来自一个dataset which gets data from a stored procedure
,这个特定的字段是一个计算出来的,so there is no column in the table for it
。我可以操作表中的所有其他字段,except for this one
. 我需要(仅用于在 datagridview 中显示)在运行时更改此列值,这会导致只读错误
这是Answer
解决用户问题的方法。
从数据集中读取数据后,它表示只读的列,尝试这样做 -ds.Tables[0].Columns["Your New Column"].ReadOnly = false;
Read the comments below for more clarity please.
忽略下面的答案和代码,因为用户的实际问题在我上面写的下面的评论中。用户应该修改他的问题。它完全错误和误导
添加一个 Winforms 项目,删除一个 DataGridView 和一个按钮。将单击处理程序添加到按钮。
在 DataGridView 中添加一列,并DataProperty
在设计器中将该列命名为“名称”。将其标记为Read-Only
。列 DataPropertyName 必须与数据库中的字段匹配。I have a class called Books with a Property called Name
. Name
因此在这种情况下应该调用它。
复制粘贴下面的代码,然后按 F5。
Click the Button to update the read-only column value.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
List<Book> books = new List<Book>();
books.Add(new Book() { Name = "C#" });
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = books;
dataGridView1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1[0,0].Value = "Winforms";
}
}
public class Book
{
public string Name { get; set; }
}
}
DataGridView 设计器代码供参考:-
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1});
this.dataGridView1.Location = new System.Drawing.Point(42, 91);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(270, 157);
this.dataGridView1.TabIndex = 1;
//
// Column1
//
this.Column1.DataPropertyName = "Name";
this.Column1.HeaderText = "Name";
this.Column1.Name = "Column1";
this.Column1.ReadOnly = true;