[英]Datagridview only adding 1 row
Im trying to add all my users accounts to a gridview but when using the foreach code it is only adding the last value of the datagridview. 我试图将所有用户帐户添加到gridview,但是使用foreach代码时,它仅添加了datagridview的最后一个值。 Is there a way to do all of them? 有办法做到所有这些吗?
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"]);
}
The DataSource property of a DataGridView object shouldn't be one row, but many. DataGridView对象的DataSource属性不应为一行,而应为多行。 So you can change your code to create a list first and apply this as the DataSource, OR you use the following method: 因此,您可以更改代码以首先创建一个列表并将其应用为数据源,或者使用以下方法:
dataGridView1.Rows.Add(GetResultsTable(row2["username"].ToString());
In the foreach loop. 在foreach循环中。
Hope it helps you out :). 希望它可以帮助您:)。
you can use one method to load the data 您可以使用一种方法来加载数据
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;
}
}
set the grid DataSource
like below 设置网格DataSource
如下所示
dataGridView1.DataSource =fillDataTable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.