Monday, October 15, 2012

how to add multiple rows from datatable to database in c#


using System;
using System.Collections.Generic;
using
 System.ComponentModel;
using
 System.Data;
using
 System.Drawing;
using
 System.Linq;
using
 System.Text;
using
 System.Windows.Forms;
using
 System.Data.SqlClient;
 

namespace
 WindowsFormsApplication1
{
    public partial class Form1 : Form    {
        public Form1()
        {
            InitializeComponent();            
        }
        DataTable dt = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
        {
            DataColumn dcname = new DataColumn("NAME");
            DataColumn dccity = new DataColumn("CITY");
            dt.Columns.Add(dcname);
            dt.Columns.Add(dccity);
            dataGridView1.DataSource = dt;
        } 
        private void btnAddToGridview_Click(object sender, EventArgs e)
        {
            DataRow dr = dt.NewRow();
            dr[0] = txtname.Text;
            dr[1] = txtcity.Text;
            dt.Rows.Add(dr);
            dataGridView1.DataSource = dt;
        }
        SqlConnection conn;
        SqlCommand comm;
        string constring = @"Data Source=server_name;Initial Catalog=DATABASE_NAME;Integrated Security=True";
        private void btnSaveToDatabase_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection(constring);
            conn.Open();
            for(int a=0;a            {
                comm = new SqlCommand("insert into TABLE_NAME values ('" + dataGridView1.Rows[a].Cells[0].Value + "','" + dataGridView1.Rows[a]
                                        .Cells[1].Value + "')", conn);
                comm.ExecuteNonQuery();
            }
            conn.Close();
            MessageBox.Show("Saved");
        }               
    }
}

No comments:

Post a Comment