【发布时间】:2015-05-02 03:30:26
【问题描述】:
当我单击 DataGridView 中的一个单元格时,值会在我的文本框上传递,但是当我的组合框出现问题时,它只是保持为空。我已经尝试过 SelectedItem 和 SelectedIndex 但它保持为空。我已经设法使用 SelectedText 将值放在我的组合框中,但是一旦我更新了我的数据库,我的组合框中就会出现 NullReferenceException,这是我的代码:
private void dgvStudentRecord_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dgvStudentRecord.Rows[e.RowIndex];
txtStudNum.Text = row.Cells["studentId"].Value.ToString();
txtStudName.Text = row.Cells["studentName"].Value.ToString();
cboSection.SelectedText = row.Cells["section"].Value.ToString();
numPrelim.Value = Convert.ToDecimal(row.Cells["prelim"].Value);
numMidterm.Value = Convert.ToDecimal(row.Cells["midterm"].Value);
numFinals.Value = Convert.ToDecimal(row.Cells["finals"].Value);
}
}
【问题讨论】:
-
当您在调试器或 QuickWatch 中将鼠标悬停在
row.Cells["section"].Value.ToString()上时,值是什么......? -
如果你把这个
cboSection.SelectedText = row.Cells["section"].Value.ToString();改成下面的cboSection.SelectedIndex = row.Cells["section"].Value;会怎么样 -
我得到一个错误,无法将字符串隐式转换为对象。
-
您想要什么:1) 将值作为新项目添加到 ComboBox.Items 或 2) 在组合框的项目集合中查找并选择该值?对 1) 使用 cb.Items.Add,对 2) 使用 cb.FindString 或 cb.FindStringExact。 (或者写你自己的发现!)
-
@TaW 2) 在组合框的 items 集合中查找并选择该值
标签: c# datagridview combobox