2013-12-15 102 views
0

我試圖將所有用戶帳戶添加到gridview,但使用foreach代碼時,它只是添加datagridview的最後一個值。有沒有辦法做到這一切?Datagridview只添加1行

public DataTable GetResultsTable(string Username) 
{ 
    using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) 
    { 
     DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'"); 
     DataTable table = new DataTable(); 
     table.Columns.Add("Username".ToString()); 
     table.Columns.Add("Motto".ToString()); 
     table.Columns.Add("Email".ToString()); 
     table.Columns.Add("Homeroom".ToString()); 
     table.Columns.Add("Health".ToString()); 
     table.Columns.Add("Energy".ToString()); 
     table.Columns.Add("Age".ToString()); 
     DataRow dr = table.NewRow(); 
     dr["Username"] = "" + row["username"] + ""; 
     dr["Motto"] = "" + row["motto"] + ""; 
     dr["Email"] = "" + row["mail"] + ""; 
     dr["Homeroom"] = "" + row["home_room"] + ""; 
     dr["Health"] = "" + row["health"] + ""; 
     dr["Energy"] = "" + row["energy"] + ""; 
     dr["Age"] = "" + row["age"] + ""; 
     table.Rows.Add(dr); 
     return table; 
    } 
} 
SqlDatabaseManager.Initialize(); 
    using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) 
    foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows) 
    { 
     dataGridView1.DataSource = GetResultsTable((string)row2["username"]); 
    } 
+0

參數化查詢。這是一個很大的禁忌:'「SELECT * FROM users WHERE username ='」+ Username +「'」'。看到這裏爲什麼:http://stackoverflow.com/questions/5468425/how-do-parameterized-queries-help-against-sql-injection –

回答

0

DataGridView對象的DataSource屬性不應該是一行,而是很多。 所以,你可以改變你的代碼先創建一個列表,然後將此作爲數據源,或者使用下面的方法:

dataGridView1.Rows.Add(GetResultsTable(row2["username"].ToString()); 

在foreach循環。

希望它可以幫助你:)。

+0

我有一個錯誤,當使用您的代碼。有沒有簡單的修復? System.Windows.Forms.dll中發生未處理的類型爲「System.InvalidOperationException」的異常 附加信息:無法將行添加到沒有列的DataGridView控件。必須先添加列。 – Fernando

0

您可以使用一種方法來加載數據

public DataTable fillDataTable() 
{ 
    // select all the columns with expected column name, here I only added 3 columns 
    string query = "SELECT username as Username, motto as Motto, mail as Email FROM users; 

    using(SqlConnection sqlConn = new SqlConnection(conSTR)) 
    using(SqlCommand cmd = new SqlCommand(query, sqlConn)) 
    { 
     sqlConn.Open(); 
     DataTable dt = new DataTable(); 
     dt.Load(cmd.ExecuteReader()); 
     return dt; 
    } 
} 

設置網格DataSource像下面

dataGridView1.DataSource =fillDataTable();