C# 数据网格视图更新只读列值

本文关键字:只读 更新 视图 数据 数据网 网格 | 更新日期: 2023-09-27 18:37:18

我有一个datagridview,它从数据库加载信息。但是,在运行时,我想允许用户更新单元格(默认情况下是只读的),但我无法执行此操作,我需要这样做,因为所有更改都保存在 db 中,但如果我重新加载它,一些颜色样式等将消失,因此我只想在请求时从 db 重新加载并对只读列的文本进行更改, 请指导。

谢谢

C# 数据网格视图更新只读列值

这是

用户的实际Question

我在数据网格视图中有一列,默认情况下(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。表 I 中的所有其他字段都可以操作,except for this one .我需要(仅用于在数据网格视图中显示目的)在运行时更改此列值,这会导致只读错误

这是解决用户问题Answer

从数据集(其表示只读的列)读取数据后,请尝试执行此操作 - ds.Tables[0].Columns["Your New Column"].ReadOnly = false;

Read the comments below for more clarity please.

忽略下面的答案和代码,因为用户的实际问题在我上面写的下面的评论中。用户应该修改他的问题。它完全错误和误导

添加一个Winforms项目,删除一个DataGridView和一个按钮。将单击处理程序添加到按钮。

在 DataGridView 中添加一列,并在设计器中将该列的DataProperty命名为"Name"。将其标记为 Read-Only 。列数据属性名称必须与数据库中的字段匹配。 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;