来自数据库的DataGridView

时间:2015-12-15 14:57:52

标签: c# winforms datagridview

当我尝试从我的数据库填充第二个dataGridview时遇到问题, 第一个dataGridView包含第二个dataGridView的值,如果我填充第二个dataGridView。

我的错误在哪里?

OleDbConnection connection = new OleDbConnection();
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();

OleDbDataAdapter oledbAdapter;
OleDbDataAdapter oledbAdapter2;

//Connection
try
{
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["DBCONNECTION"].ConnectionString;
}
catch (Exception er)
{
    MessageBox.Show("Errore " + er);
}

//First DataGridView

try
{

    string query2 = "select * from MyTable";
    connection.Open();
    oledbAdapter2 = new OleDbDataAdapter(query2, connection);
    oledbAdapter2.Fill(ds2);
    DGV1.DataSource = ds2.Tables[0]


}
catch (Exception er)
{
    MessageBox.Show("Errore " + er);
}
connection.Close(); 


    //correct assign of value
   string F = DGV1.Rows[0].Cells[2].Value.ToString();


//Second DataGridView

{

    string query = "select * from MyTable2";
    connection.Open();
    oledbAdapter = new OleDbDataAdapter(query, connection);
    oledbAdapter.Fill(ds);
    DGV2.DataSource = ds.Tables[0];

    //correct assign of value
   string B = DGV2.Rows[0].Cells[9].Value.ToString();

}
catch (Exception er)
{
    MessageBox.Show("Errore " + er);
}
connection.Close();



MyVar = DGV2.Rows[0].Cells[9].Value.ToString();


//Incorrect assign of value for DGV1, inside there are the value of DGV2 the last DataGridView Popolate  WHY??????
MyVar2 = DGV1.Rows[0].Cells[2].Value.ToString();

1 个答案:

答案 0 :(得分:-1)

尝试像这样添加DGV.DataBind():

DGV2.DataSource = ds.Tables[0];
DGV2.DataBind();

DGV1.DataSource = ds2.Tables[0]
DGV1.DataBind();