How to send data from a dataGrid that is constantly changing to an SQL table

0

is constantly changing because it gets its information with different excel files.  with this code.

public partial class PM : Form
{
    private BindingSource bindingsource1 = new BindingSource();
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    SqlConnection conexion = new SqlConnection("");
    SqlDataAdapter da;
    DataSet ds;
    DataTable dt = new DataTable();
    //SqlCommandBuilder builder;

    public PM()
    {
        InitializeComponent();
    }

    private void LLenarGrid(string archivo, string hoja)
    {
        //declaramos las variables         
        OleDbConnection conexion = null;
        DataSet dataSet = null;
        OleDbDataAdapter dataAdapter = null;
        string consultaHojaExcel = "Select * from [" + hoja + "$]";
        //esta cadena es para archivos excel 2007 y 2010
        string cadenaConexionArchivoExcel = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + archivo + "';Extended Properties=Excel 12.0;";
        //para archivos de 97-2003 usar la siguiente cadena
        //string cadenaConexionArchivoExcel = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + archivo + "';Extended Properties=Excel 8.0;";
        //Validamos que el usuario ingrese el nombre de la hoja del archivo de excel a leer
        if (string.IsNullOrEmpty(hoja))
        {
            MessageBox.Show("No hay una hoja para leer");
        }
        else
        {
            try
            {
                //Si el usuario escribio el nombre de la hoja se procedera con la busqueda
                conexion = new OleDbConnection(cadenaConexionArchivoExcel);//creamos la conexion con la hoja de excel
                conexion.Open(); //abrimos la conexion
                dataAdapter = new OleDbDataAdapter(consultaHojaExcel, conexion); //traemos los datos de la hoja y las guardamos en un dataSdapter
                dataSet = new DataSet(); // creamos la instancia del objeto DataSet
                dataAdapter.Fill(dataSet, hoja);//llenamos el dataset
                dataGridView1.DataSource = dataSet.Tables[0]; //le asignamos al DataGridView el contenido del dataSet
                conexion.Close();//cerramos la conexion
                dataGridView1.AllowUserToAddRows = false;       //eliminamos la ultima fila del datagridview que se autoagrega
            }
            catch (Exception ex)
            {
                //en caso de haber una excepcion que nos mande un mensaje de error
                MessageBox.Show("Error, Verificar el archivo o el nombre de la hoja", ex.Message);
            }
        }
    }


     private void button1_Click_1(object sender, EventArgs e)
    {
        //creamos un objeto OpenDialog que es un cuadro de dialogo para buscar archivos
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Archivos de Excel (*.xls;*.xlsx)|*.xls;*.xlsx"; //le indicamos el tipo de filtro en este caso que busque
        //solo los archivos excel
        dialog.Title = "Seleccione el archivo de Excel";//le damos un titulo a la ventana
        dialog.FileName = string.Empty;//inicializamos con vacio el nombre del archivo
        //si al seleccionar el archivo damos Ok
        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            //el nombre del archivo sera asignado al textbox
            textBox1.Text = dialog.FileName;
            string hoja = textBox2.Text; //la variable hoja tendra el valor del textbox donde colocamos el nombre de la hoja
            LLenarGrid(textBox1.Text, hoja); //se manda a llamar al metodo
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //se ajustan las
            //columnas al ancho del DataGridview para que no quede espacio en blanco (opcional)
        }
    }

That already works, but I can not find the way to send the information that is put in my dataGridView to my sql server table, because I can select a file that only has 4, 5,100, etc. number of columns, never go to be the same, I can now have in my datagridview information with 4 columns and I can save them in my sql server table if they were fixed, but I want that when my datagrid has not 50 columns that same table that was saved with 4 columns now instead of 4, keep the 50, or the x amount that exists.

My boss just wants to select the excel file he wants, pass it to the datagrid and the datagrid to the SQL Server table.

    
asked by abi 30.03.2017 в 18:48
source

1 answer

2

Easy, create a table with the following structure:

id < - autonumeric int that will be the key

xml < - field of type XML (here's the magic)

In the XML field save the datagridview information converted to XML, no matter the number of columns, you can save any XML.

NOTE: You'll have to see if your version of SQL supports XML.

To convert datagridview to XML :

DataSet ds = new DataSet(); 
DataTable dt = (DataTable)gridview.DataSource;// Conviertelo a un datatable
ds.Tables.Add(dt);
string xml = ds.GetXml();//el dataset tiene la funcion para obtener el string del XML

That parameter you send to SQL :

public void GuardarXml(int id, string xml)
{
// query sql
string insertQuery = "INSERT INTO tabla(id, xml) VALUES (@id, @xml)";

using (SqlConnection conn = new SqlConnection("Tu Cadena de conexion"))
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
    // define parameters
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    cmd.Parameters.Add("@xml", SqlDbType.Xml, xml.Length).Value = xml;

    // open connection, execute query, close connection
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}
}

Afterwards to obtain the data ... you must do the same thing that I did but in reverse:

  • Get the field XML from SQL
  • Convert it to Dataset , and then get DataTable

     StringReader reader= new StringReader(xmlData);
     DataSet ds= new DataSet();
     ds.ReadXml(reader);
    
     var dt = ds.Tables[0];
    
  • Show it in DataGridView , gridView.Datasource = dt;

  • If you do not want to send the ID you can change the code:

    public void GuardarXml( string xml)//Quitar el id de aqui
    {
    // query sql
    string insertQuery = "INSERT INTO tabla(id, xml) VALUES (@id, @xml)";
    
    using (SqlConnection conn = new SqlConnection("Tu Cadena de conexion"))
    using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
    {
        // define parameters
        //cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
        cmd.Parameters.Add("@xml", SqlDbType.Xml, xml.Length).Value = xml;
    
        // open connection, execute query, close connection
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }
    }
    
        
    answered by 30.03.2017 / 19:53
    source