2013-08-02 289 views
0

我想調試上述錯誤。以下是我的代碼。錯誤:System.NullReferenceException:對象引用未設置爲對象的實例

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();上得到一個錯誤。

我必須實例化什麼?

+3

檢查'如果(GridView1!= NULL)' – Bolu

+0

非常感謝我把後之後出現快速response.No錯誤的if語句,但GridView的不顯示。 –

+0

您的.aspx文件中是否有名爲GridView1的GridView? – sisve

回答

0
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(); 
    } 
} 
+5

在'DataSet'上使用''而不是像'SqlConnection'和'SqlCommand'和'SqlDataAdapter'這樣重要的東西。 –

+0

由於這是一個不連貫的體系結構,因此不會有資源被阻擋。我們可能只想考慮釋放DataSet ... – adityaswami89

+0

感謝您的代碼。我仍然在GridView1.DataSource = dt上得到同樣的錯誤; –

相關問題