[英]C#: DataGridView cannot be filled correctly for the second time
The following code works good when the form is load. 加载表单时,以下代码可以正常工作。 The problem is here, when I call the method again to fill the Datagridview, the datagridview columns are randomly filled with the data which is returned from DB.
问题出在这里,当我再次调用该方法填充Datagridview时,datagridview列将随机填充从DB返回的数据。
public void displayDataInGrid()
{
try
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
sda = null;
sda = new SqlDataAdapter("SELECT * FROM Product", connection);
ds = new DataSet();
sda.Fill(ds, "Product");
dataGridView1.Columns[2].DataPropertyName = "Pro_Name";
dataGridView1.Columns[3].DataPropertyName = "Pro_Type";
dataGridView1.Columns[4].DataPropertyName = "Quantity";
dataGridView1.Columns[5].DataPropertyName = "Cost_Price";
dataGridView1.Columns[6].DataPropertyName = "Market_Price";
dataGridView1.Columns[7].DataPropertyName = "Exp_Date";
dataGridView1.Columns[8].DataPropertyName = "Bar_Code";
dataGridView1.Columns[9].DataPropertyName = "Pro_Id";
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Try to put this: 尝试把这个:
' ** CODE **
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
' ** CODE **
And if it not runs, specify in SQL query the columns you need to show in the DataGridView. 如果它没有运行,请在SQL查询中指定您需要在DataGridView中显示的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.