DataGridViewLinkCell引发C#桌面CRUD应用崩溃问题求助
问题描述
我用Visual Studio C#开发了一个简单的CRUD桌面应用,已经成功连接小型SQL Server,原本一切正常。但添加两个用于编辑和删除的链接按钮后,点击查询结果中的任意其他单元格时,应用都会崩溃。
报错信息:Cannot convert DataGridViewLinkCell to DataGridViewTextBox,调试时MLA_CellContentClick方法的第一行被高亮。
相关代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace URL_API_v2 { public partial class MLA_URL : Form { private CN_MLA _CN_MLA; public MLA_URL() { InitializeComponent(); _CN_MLA = new CN_MLA(); } #region EVENTOS private void btnAgregar_Click(object sender, EventArgs e) { OpenMLAadd(); } #endregion #region Metodos Privados private void OpenMLAadd() { AgregarMLA agregarMLA = new AgregarMLA(); agregarMLA.ShowDialog(this); } #endregion private void MLA_URL_Load(object sender, EventArgs e) { Populate(); } public void Populate(string Buscar = null) { List<tablaMLA> consulta = _CN_MLA.GetMLAs(Buscar); MLA.DataSource = consulta; } private void MLA_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridViewLinkCell cell = (DataGridViewLinkCell)MLA.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cell.Value.ToString() == "EDITAR") { AgregarMLA agregarMLA = new AgregarMLA(); agregarMLA.LoadContact(new tablaMLA { URL_ID = int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString()), URL_QUERY = (MLA.Rows[e.RowIndex].Cells[1]).Value.ToString() }); agregarMLA.ShowDialog(this); } else if (cell.Value.ToString() == "BORRAR") { BorrarMLA(int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString())); Populate(); } } private void BorrarMLA (int URL_ID) { _CN_MLA.BorrarMLA(URL_ID); } private void btnBuscar_Click(object sender, EventArgs e) { Populate(txtSearch.Text); txtSearch.Text= string.Empty; } } }
解决方案
崩溃原因是MLA_CellContentClick事件触发时,不管点击的是哪种单元格,你都强制把它转换成DataGridViewLinkCell,但普通文本单元格是DataGridViewTextBoxCell,转换失败就会报错。
修改方法:在转换前先判断当前单元格的类型,只有是链接单元格时才处理编辑/删除逻辑,其他单元格直接跳过。
修改后的MLA_CellContentClick方法代码:
private void MLA_CellContentClick(object sender, DataGridViewCellEventArgs e) { // 排除表头行,避免点击表头触发错误 if (e.RowIndex < 0) return; // 用模式匹配判断单元格类型,安全获取链接单元格实例 if (MLA.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell linkCell) { string cellValue = linkCell.Value?.ToString(); // 处理空值情况,避免空引用异常 if (string.IsNullOrEmpty(cellValue)) return; if (cellValue == "EDITAR") { AgregarMLA agregarMLA = new AgregarMLA(); agregarMLA.LoadContact(new tablaMLA { URL_ID = int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString()), URL_QUERY = MLA.Rows[e.RowIndex].Cells[1].Value.ToString() }); agregarMLA.ShowDialog(this); } else if (cellValue == "BORRAR") { BorrarMLA(int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString())); Populate(); } } }
额外优化说明:
- 增加表头行判断,避免点击表头时触发错误
- 使用
?.ToString()和空值检查,防止单元格值为空时出现空引用异常 - 用模式匹配直接获取链接单元格实例,代码更简洁安全
内容的提问来源于stack exchange,提问作者Juan Pablo Humani
相关产品推荐
相关产品推荐

