将MySQL DB中的值加载到datagrid视图中的特定列

时间:2015-02-12 14:08:15

标签: c# mysql database winforms datagrid

我想从数据库中提取数据。我只需要显示前三列(0,1,2)而不是全部。我怎么能这样做?

>     string selectQuery = "select command line goes here where.... offerMadeBy='"+cbox1.Text.ToString()+"';";
>                 MySqlConnection sqlCOnnect = new MySqlConnection(RootDBConnection.myConnection);
>                 MySqlCommand sqlCmd = new MySqlCommand(selectQuery,sqlCOnnect);
>                 MySqlDataAdapter sqlAdapter;
>                 try {
>                     sqlAdapter = new MySqlDataAdapter();
>                     sqlAdapter.SelectCommand = sqlCmd;
>     
>                     DataTable dbset = new DataTable();
>                     sqlAdapter.Fill(dbset);
>                     BindingSource bindSource = new BindingSource();
>     
>                     _dataGridView.DataSource = null;
>                     bindSource.DataSource = dbset;
>                     _dataGridView.DataSource = bindSource;
>                     sqlAdapter.Update(dbset);
>     
>     
>                     if (sqlCOnnect.State == ConnectionState.Open) {
>                         sqlCOnnect.Close();
>                     }
>                 }catch(MySqlException ex){
>                     MessageBox.Show("Can't load data from DB.\nReason:"+ex.Message);
>                 }

1 个答案:

答案 0 :(得分:0)

您只需从数据库中选择所需的字段即可。此外,您必须打开与SQL的连接并最后使用参数,例如:

string selectQuery = "select field1,field2,field3 from mytable where offerMadeBy=@param";
MySqlConnection sqlCOnnect = new MySqlConnection(RootDBConnection.myConnection);
MySqlCommand sqlCmd = new MySqlCommand(selectQuery,sqlCOnnect);
sqlCmd.Parameters.AddWithValue("@param", cbox1.Text.ToString());
try { 
       sqlCOnnect.Open()
       using (sqlCOnnect)
       {
        ....
       }
      }