从 DataGridView 单元格中的 ComboBox 访问数据

Accessing Data From ComboBox in DataGridView Cell

我在布局中声明了一个 DataGridView(称为 dataGridView1)。我试图获得的单元格值是单元格中组合框选择的结果。基于这两个链接:MSDN and SO Post 我的代码如下所示:

private void Submit_Click(object sender, EventArgs e)
{
//output data to ResultsText richtextbox to check it
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {

            foreach (DataGridViewCell cell in row.Cells)
            {
                ResultsText.Text +="\n"+ cell.Value.ToString();// getting null reference exception here

            }
        }
}

我的 DataGridView 代码实现:

 private void PopulateDataGridView()
    {
        dataGridView1.AutoGenerateColumns = false;
        DataTable dt = new DataTable();
        dt.Columns.Add("LoadCaseCol");

        DataGridViewComboBoxColumn lc = new DataGridViewComboBoxColumn();
        lc.DataSource = new List<string>() { "opt1", "opt2", "opt3", "opt4" };
        lc.HeaderText = "Select Load Cases";
        //lc.DataPropertyName = "Money";

        //DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn();
        //name.HeaderText = "Name";
        //name.DataPropertyName = "Name";

        dataGridView1.DataSource = dt;
        //dataGridView1.Columns.AddRange(name, money);
        dataGridView1.Columns.AddRange(lc);
    }

要避免 NullReferenceException 您可以使用:

ResultsText.Text +="\n"+ (cell.Value == null ? "NULL" : cell.Value.ToString());

而不是

ResultsText.Text +="\n"+ cell.Value.ToString();

(假设这是问题所在)。

已更新

问题可能是由于代码初始化组合框列引起的。 请尝试设置 DataPropertyName:

private void PopulateDataGridView()
    {
        dataGridView1.AutoGenerateColumns = false;
        DataTable dt = new DataTable();
        dt.Columns.Add("LoadCaseCol");

        DataGridViewComboBoxColumn lc = new DataGridViewComboBoxColumn();
        lc.DataSource = new List<string>() { "opt1", "opt2", "opt3", "opt4" };
        lc.HeaderText = "Select Load Cases";
        lc.DataPropertyName = "LoadCaseCol";

        dataGridView1.DataSource = dt;
        dataGridView1.Columns.AddRange(lc);
    }

如果 cell.Valuenull,当您调用 ToString() 时,您将得到一个 NullReferenceException

您可以改用 Convert.ToString(),它专门检查 null 并将其转换为空字符串(防止抛出异常):

var sb = new StringBuilder();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        sb.AppendLine(Convert.ToString(cell.Value));
    }
}

ResultsText.Text = sb.ToString();