![](/img/trans.png)
[英]System.NullReferenceException – Object reference not set to an instance of an object
[英]Error :System.NullReferenceException: Object reference not set to an instance of an object
我正在嘗試調試上述錯誤。 下面是我的代碼。
private SqlConnection SQLConn(string name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return conn;
}
protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = SQLConn("Plastics");
try
{
string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (SqlException Exception)
{
// catch exception
Response.Write("An error occured");
}
finally
{
conn.Close();
}
}
我在GridView1.DataSource = cmd.ExecuteReader();上收到錯誤
我必須實例化什么?
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string str = "User ID=username;Password=password;Data Source=Test";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from table_name";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt!=null)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.