繁体   English   中英

将值分配给对象数组中的对象时,返回null

[英]null reference exception while assigning values to objects in array of objects

我收到一个null reference exception ,我不知道如何解决它,甚至不知道为什么发生。

private void editThisToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (dataGridView1.SelectedRows.Count <= 1)
    {
        Form2 f2 = new Form2(dataGridView1.SelectedRows[0].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[2].Value));
        f2.ShowDialog();
        textBox2.Text = textBox1.Text.Replace(f2.oldtext, f2.newtext);
        this.dataGridView1.SelectedRows[0].Cells[3].Value = f2.newtext;
        this.dataGridView1.SelectedRows[0].Cells[3].Style.BackColor = Color.IndianRed;
    }
    else
    {
        ONOType[] ono = new ONOType[this.dataGridView1.SelectedRows.Count];
        int indexerr = 0;
        foreach (DataGridViewRow r in dataGridView1.SelectedRows)
        {
            ono[indexerr].newtext = this.dataGridView1.SelectedRows[indexerr].Cells[3].Value.ToString(); //null expection at ono[indexerr].newtext
            ono[indexerr].oldtext = this.dataGridView1.SelectedRows[indexerr].Cells[1].Value.ToString();
            ono[indexerr].offset = Convert.ToInt32(dataGridView1.SelectedRows[indexerr].Cells[0].Value);
            indexerr++;
        }
        Form3 f3 = new Form3(ono);
        f3.ShowDialog();
        indexerr = 0;
        for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
        {
            textBox2.Text = textBox1.Text.Replace(f3.nt[i].oldtext, f3.nt[i].newtext);
            this.dataGridView1.SelectedRows[i].Cells[3].Value = f3.nt[i].newtext;
            this.dataGridView1.SelectedRows[i].Cells[3].Style.BackColor = Color.IndianRed;
        }
    }
}

这是小野班

namespace IEditor
{
    public class ONOType
    {
        public string oldtext { get; set; }
        public string newtext { get; set; }
        public int offset { get; set; }
    }
}

问题开始于:

ONOType[] ono = new ONOType[this.dataGridView1.SelectedRows.Count];

它将所有此类的新数组定义为null,这是我不想要的,可能是由关键字“ new”引起的,而没有“ new”关键字则得到comp。 为该数组中的对象分配值时出错。

我做过的尝试是在类上添加一个ctor,以在减速时为该成员数组的每个成员分配默认值(也为oldtext / newtext / offset赋值),但是此对象数组中的对象仍然为null,我确实尝试了在get / set属性上做同样的事情,但是我还是失败了。

请在解决方案中添加说明。

您正在使用以下命令创建新的ONOType引用数组:

    ONOType[] ono = new ONOType[this.dataGridView1.SelectedRows.Count];

但是,没有创建任何实际的ONOType对象。 它只是一个变量数组,什么也没有引用。

当您尝试分配ono[indexerr].newtext在元素ono[indexerr]为空引用。

如果您这样做:

    ono[indexerr] = new ONOType();
    ono[indexerr].newtext = this.dataGridView1.SelectedRows[indexerr].Cells[3].Value.ToString();

我认为这行得通。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM