【问题标题】:datasource as readonly - C#数据源为只读 - C#
【发布时间】:2012-01-10 00:35:06
【问题描述】:

我有一个属性为 DataSource = datatable()readonly = false 的 DataGridView。 readonly 必须为 false,因为还有其他列可以编辑。如何将 DataSource 中的所有列设为只读(不可编辑)?

代码如下:

type = new DataGridViewComboBoxColumn();
        table= new DataGridView
                         {
                             DataSource = datatable(), // this returns a DataTable object
                             AllowUserToAddRows = false,
                             AllowUserToDeleteRows = false,
                             RowHeadersVisible = false,
                             MultiSelect = false,
                             Name = "AgentTable",
                             AutoSize = true,
                             ReadOnly = false,
                         };
        table.Columns.Add(CreateStartButton());        
        type.Items.Add(" some table");
        type.ReadOnly = false;
        table.Columns.Add(type);

编辑: datagridview 将包含 4 列。

  • 第一列,每个单元格都是一个按钮(只读无关紧要)
  • 第二列,每个单元格都是一个下拉框(只读为假)
  • 第三和第四列被创建为 DataTable 对象所以(只读必须为真)

所以我的问题是如何将第三列和第四列设为只读?

【问题讨论】:

  • 你的意思是:数据表中的列应该是只读的,添加的列应该是可编辑的?
  • @GertArnold:请参阅上面的编辑问题

标签: c# datagridview datasource


【解决方案1】:

创建完所有列后,应该很容易迭代列。我会使用这样的东西,但我称它为伪代码,因为我不知道 DataColumn 是否是正确的数据类型:

foreach(DataColumn col in table.Columns) {
    col.ReadOnly = true;
}

【讨论】:

  • 好吧,如果你永远不打算改变结构,那么也许只是改变 table.Columns[2] 和 table.Columns[3] 。否则,在我的 foreach 循环中添加一个条件,以根据您希望保持只读/可编辑的列名列表测试列名。
  • col.Table.Columns[4].ReadOnly = true; 给出了未设置为对象实例的异常对象引用。并且当表单加载时,该列不是只读的....该列中的某些单元格是空白的,其余的则被填充。这会是个问题吗?
猜你喜欢
  • 2019-07-19
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
相关资源
最近更新 更多