【问题标题】:Accessing Data From ComboBox in DataGridView Cell从 DataGridView 单元格中的 ComboBox 访问数据
【发布时间】:2015-03-01 20:10:58
【问题描述】:

我在布局中声明了一个 DataGridView(称为 dataGridView1)。我试图获取的单元格值是单元格中组合框选择的结果。基于这两个链接:MSDNSO 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);
    }

【问题讨论】:

  • 唯一的其他错误数据是:对象引用未设置为对象实例。是的,我现在打算在文本框中显示所有内容。我只是在测试代码。

标签: c# winforms datagridview combobox


【解决方案1】:

当您拨打ToString() 时,如果cell.Valuenull,您将获得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();

【讨论】:

    【解决方案2】:

    为了避免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);
        }
    

    【讨论】:

    • 这修复了错误,但我仍然不确定为什么我会遇到这个问题。知道是什么原因造成的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多