DataGridView隐藏staffPassword列失败及空引用异常问题求助
解决DataGridView列隐藏的NullReferenceException问题
嘿,我一眼就揪出问题所在了——你碰到的System.NullReferenceException,核心原因是你的DataGridView里压根没有叫staffPassword的列!
看你的存储过程sp_GetStaff,你把Stf.staffPassword重命名成了'Password'(用AS 'Password'),所以当loadData方法把数据填充到DataGridView后,列的实际名称是Password,不是数据库里的原始列名staffPassword。你用dataGridViewStaff.Columns["staffPassword"]去查找,得到的肯定是null,调用.Visible = false自然就抛空引用异常,而且Password列也不会被隐藏。
快速修复方案
直接把BtnViewAll_Click里的列名改成存储过程里的别名Password就行:
public override void BtnViewAll_Click(object sender, EventArgs e) { loadData(dataGridViewStaff, "SNo", "sp_GetStaff"); // 把staffPassword改成存储过程里定义的别名Password dataGridViewStaff.Columns["Password"].Visible = false; }
更可靠的优化方案(推荐)
为了避免以后再出现这种“列名不匹配”的坑,你可以通过列的DataPropertyName来查找——这个属性绑定的是数据库表的原始列名,不管你给列设置了什么显示别名都不会变:
public override void BtnViewAll_Click(object sender, EventArgs e) { loadData(dataGridViewStaff, "SNo", "sp_GetStaff"); // 通过原始数据源列名查找,更稳定 var passwordColumn = dataGridViewStaff.Columns.Cast<DataGridViewColumn>() .FirstOrDefault(col => col.DataPropertyName == "staffPassword"); if (passwordColumn != null) { passwordColumn.Visible = false; } }
这种方式就算以后你修改了存储过程里的列别名,代码也不会出错,容错性更高。
顺便提个CellClick里的潜在问题
看你的DataGridViewStaff_CellClick方法,这里的staffID变量是从哪来的?我没看到你给它赋值啊!如果这个变量是空的,后续调用存储过程sp_GetStaffPassword肯定会出错。建议改成从选中的行里获取Staff Id:
private void DataGridViewStaff_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex > -1 && e.ColumnIndex > -1) { string cs =....... // 先从选中行拿到Staff Id string staffID = dataGridViewStaff.Rows[e.RowIndex].Cells["Staff Id"].Value.ToString(); SqlConnection con = new SqlConnection(cs); SqlCommand cmd = new SqlCommand("sp_GetStaffPassword", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@staffId", staffID); con.Open(); DataTable dt = new DataTable(); SqlDataReader sdr = cmd.ExecuteReader(); dt.Load(sdr); con.Close(); txtPassword.Text = dt.Rows[0][0].ToString(); txtConfirmPassword.Text = dt.Rows[0][0].ToString(); txtPhoneNo.Text= dataGridViewStaff.Rows[e.RowIndex].Cells["Mobile No."].Value.ToString(); } }
内容的提问来源于stack exchange,提问作者hornet
相关产品推荐
相关产品推荐

