我正在制作一个数据库来存储以前的项目,因为我正在清理我的硬盘。
我目前正在使用DataGrid存储所有信息,我有一个链接部分。我希望链接部分突出显示,所有文件都有不同的URL,所以我不能使用OnClick Process.Start。我找到了许多我尝试过的无法使用的教程。
以下是代码。它有3列,试图将URL放在最后。 当我单击列中的URL时,我希望它能够加载浏览器并打开网站。
public Form1()
{
InitializeComponent()
dataGridView1.Rows.Add
(
"TrustEditz",
"GTA",
"http://www.mediafire.com/download/e4qd1r5r4170onj/Vert.rar"
);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
/// This object will have the link text in it
// It's important to note that we are casting DataGridViewCell Class to
// sender object
var theComponent = (DataGridViewCell)sender;
var val = (string)theComponent.Value.ToString(); // Or theComponent.Value.ToString();
if (val == (string)theComponent.Value.ToString())
{
switch (val)
{
case "http://www.mediafire.com/download/e4qd1r5r4170onj/Vert.rar":
Process.Start("http://www.mediafire.com/download/e4qd1r5r4170onj/Vert.rar");
break;
default:
break;
}
}
}
我的应用程序中仍然出现Unhandeled异常。如果单击“继续...”
答案 0 :(得分:0)
单击链接(或单元格/行)时,您需要将事件绑定到该操作。所以
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// Check that it is a valid row and it was in column #3 0 based indexing
if (!dataGridView1.CurrentCell.ColumnIndex.Equals(2) || e.RowIndex == -1)
{
return;
}
// Check if the current cell is not null and that the value is not null
if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.Value == null)
{
return;
}
// ******EDIT******
// Before I said to cast the DataGridViewCell Object
// This is wrong, since the sender is the DataGrid itself not the cell object
// Below the code is using the variable e to reference the events row index
var theRow = dataGridView1?.Rows?[e.RowIndex];
var theCell = theRow?.Cells?[2];
var val = theCell?.Value?.ToString();
if (string.IsNullOrEmpty(val))
{
MessageBox.Show("The cell value is not assigned");
return;
}
switch(val)
{
case "http://www.mediafire.com/download/e4qd1r5r4170onj/Vert.rar":
// Do something
break;
default:
break;
}
}
这里的关键是你将点击动作与特定的单元格内容取消关联。