【问题标题】:Winform DataGridViewLinkColumn ReadOnly property not workingWinform DataGridViewLinkColumn ReadOnly 属性不起作用
【发布时间】:2016-03-17 23:11:56
【问题描述】:

在我的 VS2015 Winform 应用程序中,有一个 DataGridView 控件绑定到绑定到 SQL 数据库的 BindingSource。网格有四列:ID、URL、名称、类型。 URL 列是DataGridViewLinkColumn,其ReadOnly 属性默认设置为False。我可以编辑名称和类型列,但 URL 列显示为只读。为什么?如何使 URL 列可编辑?

【问题讨论】:

  • DataGridViewLinkColumn 不可编辑。它仅将内容显示为链接。
  • 数据实际上是在数据库中更改(读写)还是仅在表单上更改(仍然可以是只读的,只是“戏弄”你)?

标签: winforms datagridview bindingsource datagridviewlinkcolumn


【解决方案1】:

正如雷扎所说:

DataGridViewLinkColumn 不可编辑。

因此,要编辑此类列中的单元格,您必须根据需要将其转换为 DataGridViewTextBoxCell。例如,如果我订阅了DataGridView.CellContentClick 来处理点击链接,那么我将处理CellDoubleClick 来进行单元格转换:

private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = new DataGridViewTextBoxCell();
        this.dataGridView1.BeginEdit(true);
    }
}

输入值并离开单元格后,应使用CellValidated 验证新值是否为URI,然后再将单元格转换回DataGridViewLinkCell

private void DataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

        if (Uri.IsWellFormedUriString(cell.EditedFormattedValue.ToString(), UriKind.Absolute))
        {
            cell = new DataGridViewLinkCell();
        }
    }
}

警告

  • 这仅在“URL”列的数据是字符串时才对我有用,因此在绑定后,该列默认为 DataGridViewTextBoxColumn - 强制手动转换为链接单元格开头:

    private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if (Uri.IsWellFormedUriString(r.Cells["URL"].Value.ToString(), UriKind.Absolute))
            {
                r.Cells["URL"] = new DataGridViewLinkCell();
            }
        }
    }
    
  • 从一开始就将“URI”列设置为DataGridViewLinkColumn 允许将单元格成功转换为TextBox 类型。但是当转换回链接单元格时,调试显示转换发生,但单元格格式和行为失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2020-11-07
    • 2019-12-11
    • 2020-01-24
    • 2020-11-29
    相关资源
    最近更新 更多