【问题标题】:Replace Hyperlink with button in Datagridview?用Datagridview中的按钮替换超链接?
【发布时间】:2016-08-04 15:19:29
【问题描述】:
我可以使用这个在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 文本?
【问题讨论】:
标签:
c#
winforms
button
datagridview
hyperlink
【解决方案1】:
你当然可以。
这是一个仅适用于一个 Cell 的示例:
DataGridViewButtonCell bCell = new DataGridViewButtonCell();
dataGridView1[col, row] = bCell;
现在您需要确定Button 的Text 应该是什么:它将显示Cell 的Value。这可能没问题,但如果您的文件名包含较长的路径等。您可能希望显示较短的文本并将名称存储在 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();