如何直接填充DataGridView的单元格

时间:2015-12-09 11:56:22

标签: c# datagridview

我想直接在数据网格的单元格中插入数据然后将其发送到数据库,但是这些行没有添加数据,插入后它们保持为空,尽管数据出现在cells.value中我使用F11逐行运行代码。数据库与数据网格链接良好,因为当我使用文本框将数据放入数据网格单元格时,它可以正常工作,但是当我通过以下代码将数据直接放入单元格时它不起作用:

 public void BD_Conexao()
    {
        try
        {
            OdbcConnection con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
            con.Open();
        }

        catch (Exception ex)
        {
            Console.WriteLine("Erro na ligação à base de dados. \n{0}", ex.Message);
            return;
        }

    }
public void Consulta()
    {
        con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
        con.Open();

        OdbcCommand Command = con.CreateCommand();
        Command.CommandText = "select lojas.Id, lojas.NIF, lojas.Loja, lojas.Bloqueado, lojas.DataFim, lojas.lastupdate, lojas.Nome";


        Command.CommandType = CommandType.Text;
        Command.Connection = con;

        OdbcDataAdapter adapter = new OdbcDataAdapter();
        adapter.SelectCommand = Command;

        DataSet dataSet = new DataSet();
        adapter.Fill(dataSet);

        grid_lic.DataSource = dataSet;

        grid_lic.DataMember = dataSet.Tables[0].TableName;
      }

 private void bt_preencher_Click(object sender, EventArgs e)
 {
   BD_Conexao();

   string DataFim = dateTimePicker.Value.ToString("yyyy-MM-dd");
   string lastupdate = dateTimePicker2.Value.ToString("yyyy-MM-dd");
   Commandtext = "insert into lojas (NIF,Loja,bloqueado, DataFim, lastupdate, Nome) values (@NIF,@Loja,@Bloqueado,@DataFim,@lastupdate,@Nome)";

   OdbcCommand Command = new OdbcCommand(Commandtext, con);

   Command.CommandType = CommandType.Text;

   Command.Parameters.AddWithValue("@NIF", grid_lic.CurrentRow.Cells[1].Value);
   Command.Parameters.AddWithValue("@Loja", grid_lic.CurrentRow.Cells[2].Value);
   Command.Parameters.AddWithValue("@Bloqueado", checkBox_bloq.Checked);
   Command.Parameters.AddWithValue("@DataFim", grid_lic.CurrentRow.Cells[4].Value);
   Command.Parameters.AddWithValue("@lastupdate", grid_lic.CurrentRow.Cells[5].Value);
   Command.Parameters.AddWithValue("@Nome", grid_lic.CurrentRow.Cells[6].Value);

   Command.ExecuteNonQuery();
   Consulta();
}

有什么问题?

1 个答案:

答案 0 :(得分:0)

data gird需要一个数据源属性来填充数据,所以:

1)使用insert语句将所有数据插入数据库。

2)然后你需要做这样的事情来绑定数据库中的数据:

      string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
        string sql = "SELECT * FROM Authors";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
        DataSet ds = new DataSet();
        connection.Open();
        dataadapter.Fill(ds);
        connection.Close();
        dataGridView1.DataSource = ds;