显示异常 - 未将对象引用设置为对象的实例

时间:2013-08-29 04:30:27

标签: c# .net

在这行代码dr = dt.Rows[k];我得到异常Object reference not set to an instance of an object.我错了?

public partial class EditEngClgList : Form
        { 
          public EditEngClgList()
            {
                InitializeComponent();
                try
                {
                    acccon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
                    acccon.Open();
                }
                catch (Exception err)
                {
                    MessageBox.Show("Error:" + err);
                }
                string sql = "Select * From EngColeges order by EngClgID";
                da = new OleDbDataAdapter(sql, acccon);
                cmdb = new OleDbCommandBuilder(da);

                dt1 = new DataTable();
                da.Fill(dt1);
                bs = new BindingSource();
                bs.DataSource = dt1;

                dataGridView1.DataSource = bs;
                dataGridView1.Columns[1].Visible = false;
            }
     private void button4_Click(object sender, EventArgs e)
            {
                List<int> checkedclg = new List<int>();
                DataRow dr;
                List<int> checkedclgid = new List<int>();
                for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
                {
                    if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
                    {
                        checkedclg.Add(i);
                        checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value)); 
                    }
                }
                foreach (int k in checkedclg)
                {
                    dr = dt.Rows[k]; //this datatable object I hae created in another function              
                    dt.Rows[k].Delete();
                    foreach (int j in checkedclgid)
                    {
                        OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = @clgID", acccon);
                        oleDbCommand.Parameters.Add("@clgID", OleDbType.Integer).Value = j;
                        oleDbCommand.Prepare();
                        oleDbCommand.ExecuteNonQuery();

                    }
                }
            }

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

在该行上放置断点 - 很可能dt对象为空。

为了解决k可能大于Rows.Count的注释,我想如果问题出现在k,你会得到一个异常,表明索引超出范围(IndexOutOfBoundsException )。