[英]C#: DataGridView shows only one row
我在C#中的datagridview有問題。 我通過查詢從mysql數據庫中獲取數據。 但是由於某種原因,結果的第一行僅顯示在gridview中。 我使用以下代碼執行此操作:
MySqlCommand command = new MySqlCommand(query, Globals.Connection);
reader = command.ExecuteReader();
while (reader.Read())
{
object[] dataset = new object[7];
dataset[0] = reader["sto_name"];
dataset[1] = reader["esss"];
dataset[2] = reader["onl_name"];
dataset[3] = reader["rpc_id"];
if (reader["datum_aufstellung"].ToString() != "0")
{
dataset[4] = getDate(reader["datum_aufstellung"]);
}
else
{
dataset[4] = "Kein Datum gesetzt";
}
if (reader["datum_abbau"].ToString() != "0")
{
dataset[5] = getDate(reader["datum_abbau"]);
}
else
{
dataset[5] = "Kein Datum gesetzt";
}
dataset[6] = reader["id"];
dataGridView1.Rows.Add(dataset);
}
它起作用了,前面的幾行代碼。 ^^您有什么主意嗎?
更新: while循環的內容僅執行一次。 在我問這里問題之前,我也想知道這個事實。 但是,如果我在MySQL客戶端中執行查詢,則它返回的行多於一行。
更新2:我注意到,盡管注釋了while循環的全部內容,但循環的執行時間與查詢結果中的行完全相同。 有任何想法嗎?
更新3:似乎之后的一切
dataGridView1.Rows.Add(dataset);
不執行。 不僅在循環中,而且在整個功能中。 但為什么?
解決的問題:此處發布的代碼沒有任何問題。 當在dgv中輸入一行時,我在代碼的其余部分中都有一個事件,該事件執行了某些操作。 我想當這種情況發生時,循環就中斷了。 刪除該事件后,dgv已正確填充。
檢查網格上的RowCount屬性。 如果將其增加到所需的行數,則可以將其設置為1。
您應該使用DataAdapter
並使用它來填充DataTable。 創建一個用於獲取數據的方法,如下所示:
public DataTable GetDataTable()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection (@"YourCOnnectionString"))
{
using (SqlCommand cmd = new SqlCommand (query, con))
{
var adaptor = new SqlDataAdapter ();
adaptor.SelectCommand = cmd;
con.Open();
adaptor.Fill(dt);
return dt;
}
}
}
然后,您可以使用DataGrid引用它:
DataTable Result = GetDataTable();
DatagridView1.DataSource = Result;
還有另一種簡單的方法。 您可以使用DataTable代替數據集,並將dataGridView的DataSource設置為該DataTable。 它不僅可以解決您的問題,還可以使用它輕松設置列標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.