以下代码有什么问题? GridView GridView1根本没有显示在页面上。
public void display_range_mark()
{
int from = int.Parse(ddl_from_mark.SelectedValue.ToString());
int to = int.Parse(ddl_to_mark.SelectedIndex.ToString());
DataTable dt=Data.DoSomthing(string.Format("select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>='{0}' AND tn.NomreAdad<='{1}' AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars",from,to));
//DataTable data = Data.DoSomthing(string.Format("select t.Name,t.Id from tblStd t where t.DateSabt='{0}'", p.GetYear(DateTime.Now)));
GridView1.DataSource = dt;
GridView1.HeaderRow.Cells[0].Text = "نام";
GridView1.HeaderRow.Cells[1].Text = "نام خانوادگی";
GridView1.HeaderRow.Cells[2].Text = "شماره دانش آموزی";
GridView1.HeaderRow.Cells[3].Text = "درس";
GridView1.HeaderRow.Cells[4].Text = "نمره";
GridView1.DataBind();
}
我收到了这个错误:
异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。
该行发生错误:
GridView1.HeaderRow.Cells[0].Text = "نام";
顺便说一下,Data.DoSomthing的代码就像下面一样(它位于类数据库中):
SqlConnection sc = new SqlConnection(@"Data Source=.;Initial Catalog=School;Integrated Security=True");
public DataTable DoSomthing(string text)
{
sc.Open();
DataTable data = new DataTable();
try
{
SqlCommand command = new SqlCommand();
command.Connection = sc;
command.CommandType = CommandType.Text;
command.CommandText = text;
SqlDataAdapter sd = new SqlDataAdapter(command);
sd.Fill(data);
if (data.Rows.Count == 0)
data = null;
}
catch (Exception ex)
{
sc.Close();
return null;
}
finally
{
if (sc.State != ConnectionState.Closed)
{
sc.Close();
}
}
return data;
}
答案 0 :(得分:2)
连接到数据库并获取值的连接对象在哪里?
执行此操作的方法:
string query="select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>=@from AND tn.NomreAdad<=@to AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars";
//Create Sqlconnection object
using(SqlConnection con = new SqlConnection(connectionstring))
{
//open the connection
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, con);
//To avoid sql injection using parameters
sda.Paramaters.AddWithValue("@from",from);
sda.Paramaters.AddWithValue("@to",to);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}