简体   繁体   中英

Insert data from SQL query into a DataGridView C#

First of all, I have to say that I am new with C#. What I want to do is** display some information through a DataGridView**. I get a row from an SQL query and want to display this row using DataGridView.

What is the most efficient way to do this? I have a function that gets the values ​​from the sql query and returns it with a string[].Would be better return a DataGridView?

And then, how can I assign this values to the DataGridView? This is what I am trying but doens't work.

        string[] x = new string[6];
        DataGridView newdata = new DataGridView();
        x = fbd.consultar_Estado_Etiqueta(etiq);

        DataGridViewRow row = new DataGridViewRow();

        row.Cells[1].Value = x[1];
        row.Cells[2].Value = x[2];
        row.Cells[3].Value = x[3];
        row.Cells[4].Value = x[4];
        row.Cells[5].Value = x[5];
        row.Cells[6].Value = x[6];
        dataGridView_infoEtiqueta.Rows.Add(row);

It depends on how do you manage your connection with th database. The simplest way is to use Dataset and define it as Datasource for your grid. Something like this:

var select = "SELECT * FROM MYTABLE";
var connection = new SqlConnection(ConnectionString); // connection string!
var Adapter = new SqlDataAdapter(select, connection); 
var Builder = new SqlCommandBuilder(Adapter);
var myDataSet = new DataSet();
Adapter.Fill(myDataSet);
dataGridView_infoEtiqueta.DataSource = myDataSet.Tables[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM