解决方案
来自msdn: Quote:
尝试取消引用空对象引用时引发的异常。
这里是链接: NullReferenceException [ ^ ] 此异常表示您尝试访问不存在的对象。最好在使用引用之前检查空值。 最好:使用调试器 F5开始调试 F9切换断点 F10跨越 F11步入 祝你有个美好的一天。
im using sqlserver2008,Visual studio 2010 on windows 7 ultimate.i have school database which contains student table.im not able to access the data from the backend.whats wrong in this code.object reference not set to an instance of an object.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFirstsample { public partial class Form1 : Form { private SqlConnection cn; private SqlDataAdapter da; private SqlCommand cmd; private DataSet ds; private string strcon; private string strq; private int icounter; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { strcon="Data Source=HP-PC//SQLEXPRESS;Initial Catalog=school;Integrated security=true; "; cn = new SqlConnection(strcon); strq = "select * from student"; cn.Open(); da = new SqlDataAdapter(strq,cn); ds = new DataSet(); da.Fill(ds); textBox1.Text = ds.Tables[0].Rows[0]["id"].ToString(); textBox2.Text = ds.Tables[0].Rows[0]["name"].ToString(); } private void button1_Click(object sender, EventArgs e) { icounter = 0; textBox1.Text = ds.Tables[0].Rows[0]["id"].ToString(); textBox2.Text = ds.Tables[0].Rows[0]["name"].ToString(); } private void button2_Click(object sender, EventArgs e) { int irowcount = ds.Tables[0].Rows.Count - 1; if (icounter < irowcount) { icounter++; textBox1.Text = ds.Tables[0].Rows[icounter]["id"].ToString(); textBox2.Text = ds.Tables[0].Rows[icounter]["name"].ToString(); } else { MessageBox.Show("you are already on the last record"); } } private void button3_Click(object sender, EventArgs e) { if (icounter > 0) { icounter--; textBox1.Text = ds.Tables[0].Rows[icounter]["id"].ToString(); textBox2.Text = ds.Tables[0].Rows[icounter]["name"].ToString(); } else { MessageBox.Show("you are already on the first record"); } } private void button4_Click(object sender, EventArgs e) { icounter = ds.Tables[0].Rows.Count - 1; textBox1.Text = ds.Tables[0].Rows[icounter]["id"].ToString(); textBox2.Text = ds.Tables[0].Rows[icounter]["name"].ToString(); } } } 解决方案 from msdn: Quote:The exception that is thrown when there is an attempt to dereference a null object reference.
here is the link: NullReferenceException[^] this exception means that you tried to access a non-existing object. it is better to check for null values before using references. the best: use the debugger F5 start debug F9 toggle breakpoint F10 step over F11 step into have a good day.
更多推荐
system.NullReferenceException有问题
发布评论