Passing data from a selected row of a datagridview to an SQL table

0

Good community I hope you are very well. My question is the following: I have a datagridview in which I load certain information according to a search that I do, from that datagridview I can select 1, 2, 3 or all the rows if I want it. Now I want that by pressing a button I can store the row (s) that I select from the datagridview in an SQL table. What happens is that I do not know how to do to get only and only the values of the row (s) that I select and thus be able to save them in the database.

Summing up: how can you pass the value of 1 single row selected (or all that the user selects) from a datagridview to a table in SQL

    
asked by sullivan96 19.02.2018 в 22:55
source

3 answers

0

in the properties of your DataGridView you will mark in Selection Mode = FullSelectedRow so that it allows you to select all the values of your row.

After that, in the CellClick method of your DataGridView you will add the following code:

private void DataGridView1_CellClick(object sender, 
               DataGridViewCellEventArgs e){
     //Teniendo en cuenta que DataGridView1 es tu DataGridView.
     DataGridViewRow fila = DataGridView1.Rows[e.RowIndex];

     //Supongamos que tengo el campo nombre en mi DataGridView
     String nombre = Convert.ToString(fila.Cells["nombre"].Value);
     //Ahi extrage el valor de la columna uno por ejemplo, de la misma forma tu lo haras para todos tus campos.

}

Later you will insert your data with a query, passing as parameters your values extracted from the row.

    
answered by 19.02.2018 в 23:04
0
foreach (DataGridViewRow dgv in dataGridView1.Rows)
{
if (Convert.ToInt32(dgv.Cells[0].Value) == 1) //Fila seleccionada, yo lo hice con un checkbox
dt.Rows.Add(dgv.Cells[1].Value, dgv.Cells[2].Value, dgv.Cells[3].Value); //Agrega valores de cada columna
}
    
answered by 14.03.2018 в 00:18
0

I will give you a solution. in this case it is using a micro-ORM (Dapper)

public partial class AdressBokPerson
    {
        public long Id{ get; set; }
        public string Name{ get; set; }
        public string LastName{ get; set; }
        public string Mail { get; set; }
    }

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
   // puedes selecionar el row y convertir el objeto DataBoundItem a un tipo especificado:
AdressBokPerson currentObject = (AdressBokPerson)dataGridView1.CurrentRow.DataBoundItem;



}

void insert(){

// una vez realizado tu conexion e instalado dapper

// con dapper nos permite mappear la informacion que nosotros deseemos.
// este es el metodo de insertar.
var Result = Conexion.Execute("INSERT INTO AdressBokPerson ( Name, LastName, Mail )
VALUES (@Name, @LastName, @Mail )", currentObject );

Console.WriteLine(Result);
}

This is a way to do it. I hope I helped you

    
answered by 30.11.2018 в 18:27