2014-02-28 58 views
-1

我想在DataGridView.here顯示我的DB表數據是我的代碼使用選擇查詢,顯示在數據網格視圖數據

private void button1_Click(object sender, EventArgs e) 
{    
    SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + 
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True"); 

    myConnection.Open(); 

    SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection); 

    SqlDataAdapter adp = new SqlDataAdapter(objcmd); 

    DataTable dt = new DataTable(); 

    //adp.Fill(dt); 

    DataGridView.DataSource = adp.Fill(dt); 



} 

代碼現在沒有給予任何錯誤,但但它dosent顯示我的表格中的數據在我的網格?

回答

1

您正在使用class名稱,而不是DataGridView對象(實例)名稱,請在HTML是什麼DataGridView ID /名稱,它可能是贏得窗體和你沒有DataBind方法那裏。 DataBind方法是針對ASP.net的GridView定義的。查找更多關於DataGridView的信息here

DataGridViewObject.DataSource = adp.Fill(dt); 
0

創建的DataGridView的一個實例:

DataGridView dview = new DataGridView(); 
.... 
dview.DataSource = adp.Fill(dt); 
dview.DataBind(); 
+0

我已經做到了這一點 數據表dt = new DataTable(); adp.Fill(dt); DataGridView DView = new DataGridView(); DView.DataSource = dt; DView.DataBind(); 它不識別DataBind(); – user3085866

0

您直接訪問的DataGridView屬性和數據,要來試圖添加到類。您需要首先創建一個DataGridView的實例。然後將該datable分配給該對象。 比將數據綁定到DataGridView,否則數據不綁定到控件並且不會顯示。

DataGridView view = new DataGridView(); 
dview.DataSource = adp.Fill(dt); 
dview.DataBind(); 
+0

我已更正我的代碼,並且數據綁定不是必需的,因爲我在Google搜索後瞭解到它,代碼沒有給出任何錯誤,但它不在網格視圖中顯示錶格數據,我在這裏丟失了什麼,沒有執行查詢,這是我認爲我做錯了 – user3085866

+0

對不起,你沒有執行查詢。您將需要添加objcmd.ExecuteReader() – Kbaugh

+0

現在它引發此錯誤已經有一個打開的DataReader與此命令關聯,必須先關閉 – user3085866

0

你是不是exectuting查詢

myConnection.Open(); 
    SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection); 
    DataTable dt = new DataTable(); using 
    (SqlDataReader sqlDataReader = objcmd.ExecuteReader()) 
    { 
     dt.Load(sqlDataReader); 
     sqlDataReader.Close(); 
    } 
    DataGridView dataGridView1 = new DataGridView(); 
    dataGridView1.DataSource = dt; 
1

這就是答案我quetion,希望它可以幫助別人誰是新的這個

SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;" + "Integrated Security=True"); 
myConnection.Open(); 
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection); 
//objcmd.ExecuteNonQuery();  
SqlDataAdapter adp = new SqlDataAdapter(objcmd); 
DataTable dt = new DataTable(); 
adp.Fill(dt); 
//MessageBox.Show(dt.ToString()); 
dataGridView1.DataSource = dt; 
相關問題