未将对象引用设置到对象的实例。求大神们帮助,,在线等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetDataset("select * from TestID").Tables[0];
GridView1.DataBind();
}
}
private DataSet GetDataset(string sql)
{
string strConn = "data source=PC-20130111CRCF\\SQL;initial catalog=Test;uid=sa;password=sa";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
return ds;
}
private void Write()
{
DataTable dt = new DataTable();
string strConn = "data source=PC-20130111CRCF\\SQL;initial catalog=Test;uid=sa;password=sa";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
dt.Columns.Add("教工号", typeof(string));
dt.Columns.Add("姓名", typeof(string));
dt.Columns.Add("周次", typeof(string));
dt.Columns.Add("星期", typeof(string));
dt.Columns.Add("节次", typeof(string));
dt.Columns.Add("课程", typeof(string));
dt.Columns.Add("考勤情况", typeof(string));
for (int i = 0; i < GridView1.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
dr["教工号"] = GridView1.Rows[i].Cells[0].Text;
dr["姓名"] = GridView1.Rows[i].Cells[1].Text;
dr["周次"] = ((DropDownList)GridView1.Rows[i].Cells[2].FindControl("GridView1")).SelectedValue;
dr["星期"] = GridView1.Rows[i].Cells[3].Text;
dr["节次"] = GridView1.Rows[i].Cells[4].Text;
dr["课程"] = GridView1.Rows[i].Cells[5].Text;
dr["考勤情况"] = GridView1.Rows[i].Cells[6].Text;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button1_Click1(object sender, EventArgs e)
{
Write();
}
}
[解决办法]
检查你所有带索引的对象,比如GridView1.Rows[i].Cells[0]是否为null,调试到报错的那一条,逐个看看各个对象是否为null