总是出现错误消息"在调用' Fill'之前,尚未初始化SelectCommand属性。"

时间:2014-07-28 06:40:15

标签: c# odbc

 private void toolStripButton1_Click(object sender, EventArgs e)
 {
     OdbcConnection conn = new OdbcConnection();
     conn.ConnectionString =
              "Dsn=mdc;" +
              "Uid=root;" +
              "Pwd=;";
     OdbcCommand cmd = new OdbcCommand("select * from tbl_delivery");
     cmd.CommandType = CommandType.Text;

     DataSet dt = new DataSet();
     OdbcDataAdapter ds = new OdbcDataAdapter();
     ds.Fill(dt);
     tbl_deliveryDataGridView.DataSource = dt; 
     try
     {
         conn.Open();
         cmd.ExecuteNonQuery();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
}

每次我要运行程序时都会出现错误,我不知道错误在哪里。我尝试编辑代码但仍然会出现错误。

1 个答案:

答案 0 :(得分:0)

您收到错误是因为您没有将OdbcCommand分配给OdbcDataAdapter并尝试执行Fill方法。你应该像这样将OdbcCommand分配给OdbcDataAdapter

 OdbcDataAdapter ds = new OdbcDataAdapter(cmd,conn);

然后尝试填充DataTable

    conn.Open();
    DataSet dt = new DataSet();
    OdbcDataAdapter ds = new OdbcDataAdapter();
    ds.Fill(dt);
    tbl_deliveryDataGridView.DataSource = dt;