将数据网格视图中的超链接替换为按钮



我可以使用它在DataGridView中创建Hyperlink

  private void dgvCatalogue_CellContentClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
    {
        string filename = dgvCatalogue[e.ColumnIndex, e.RowIndex].Value.ToString();
        if (e.ColumnIndex == 5 && File.Exists(filename))
        {
            Process.Start(filename);
        }
    }

是否可以将hyperlink文本替换为图像/按钮?

当然可以。

以下是一个仅针对一个Cell的示例:

DataGridViewButtonCell bCell = new DataGridViewButtonCell();
dataGridView1[col, row] = bCell;

现在您需要决定ButtonText应该是什么:它将显示CellValue。这可能很好,但如果你的文件名包括一个很长的路径等。你可能想显示一个较短的文本,并将名称存储在cell.Tag中:

string someFileName=  "D:\temp\example.txt";
dataGridView1[col, row].Tag = someFileName;
dataGridView1[col, row].Value = Path.GetFileNameWithoutExtension(someFileName);

如果你想让整列显示按钮,你可以这样做:

DataGridViewButtonColumn bCol = new DataGridViewButtonColumn();
dataGridView1.Columns.Add(bCol);

相同的联合降级适用于按钮列中的单元格。

要测试你是否在按钮单元格上,你可以写:

DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (cell.OwningColumn.CellType == typeof(DataGridViewButtonCell)) ..

要通过Tag访问值,请使用以下代码:

if (cell.Tag != null) string filename = cell.Tag.ToString();

最新更新