如何关闭frm_search对话框并加载frm_item的dtgItem数据网格
问题修复方案
一、解决frm_search无法关闭的问题
你的frm_search代码存在两个核心问题:
- 新建了全新的frm_item实例,而非将值传递给原本调用frm_search的窗口,导致弹出新窗口后,原frm_search的关闭逻辑被阻塞。
item.ShowDialog()会阻塞代码执行,后续的DialogResult设置和Close()根本无法运行。
修改后的frm_search代码:
// 移除这里的frm_item实例声明 public string MyValue { get; set; } private void dgList_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { // 通过Owner属性获取调用当前对话框的原frm_item窗口 var item = Owner as Request.frm_item; if (item == null) return; switch (MyValue) { case "CATEGORY": item.txtCat.Text = dgList.CurrentRow.Cells[0].Value.ToString(); item.cat_id.Text = dgList.CurrentRow.Cells[1].Value.ToString(); // 设置DialogResult后,ShowDialog会自动关闭对话框 DialogResult = DialogResult.OK; break; } } }
同时修改frm_item中打开frm_search的代码,传递当前窗口为Owner:
private void txtCat_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete) { Software.frm_search search = new Software.frm_search(); search.MyValue = "CATEGORY"; // 将当前窗口设为frm_search的Owner,用于后续值传递 search.Owner = this; DialogResult result = search.ShowDialog(); // 后续逻辑保持不变 if (result == DialogResult.OK) { // ... 数据查询代码 } search.Dispose(); } }
二、解决dtgItem数据网格无法显示数据的问题
1. 修复SQL注入风险与查询语法问题
原代码用字符串拼接SQL存在注入风险,还可能因格式错误导致查询失败,改为参数化查询(或确保数值安全后拼接),同时增加有效性校验:
if (result == DialogResult.OK) { // 先校验cat_id是否为有效整数 if (!int.TryParse(cat_id.Text, out int cate_id)) { MessageBox.Show("无效的分类ID"); return; } DataTable dt = new DataTable(); // 使用参数化查询(推荐),需根据你的ConObj实现调整参数传递方式 string sql = "SELECT code as 'Code Number', item_name as 'Item Name', active as 'Active' FROM items WHERE id_category = @cateId"; // 示例:如果ConObj支持参数,可传递SqlParameter对象 // dt = ConObj.exec(sql, new SqlParameter("@cateId", cate_id)); // 若ConObj不支持参数,因已校验cate_id为整数,可安全拼接 dt = ConObj.exec($"SELECT code as 'Code Number', item_name as 'Item Name', active as 'Active' FROM items WHERE id_category = {cate_id}"); dtgItem.DataSource = dt; // 强制刷新数据网格,确保数据显示 dtgItem.Refresh(); // 若未手动配置列,开启自动生成列 dtgItem.AutoGenerateColumns = true; ConObj.disconnect(); }
2. 额外排查点
- 检查
ConObj.exec方法是否正确返回DataTable:调试时查看dt是否包含数据行。 - 确认数据库中
id_category字段类型与cate_id一致(均为int类型)。 - 若手动配置了dtgItem的列,需保证列的
DataPropertyName与查询结果的列名完全匹配(注意空格和大小写)。
内容的提问来源于stack exchange,提问作者Raffy
相关产品推荐
相关产品推荐

