以下代码在加载表单时效果很好。问题出在这里,当我再次调用方法来填充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);
}
}
答案 0 :(得分:0)
试着说出来:
' ** CODE **
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
' ** CODE **
如果它没有运行,请在SQL查询中指定您需要在DataGridView中显示的列。