Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store multiple records in SQL Server using DataGridView

I'm trying to insert 5 records into a SQL Server database table from DataGridView using C#.

From my code it takes input of several records but insert only first record in database. Can anybody help me to save 5 records in database by a single click of save button?

Here is my code:

    DataSet ds = new DataSet();

    SqlConnection cs = new SqlConnection(@"Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True");

    SqlDataAdapter da = new SqlDataAdapter();

    SqlCommand cmd = new SqlCommand();

    BindingSource Input = new BindingSource();
    DataView dview = new DataView();

    private void Form1_Load(object sender, EventArgs e)
    {
        //create a DataGridView Image Column
        DataGridViewImageColumn dgvImage = new DataGridViewImageColumn();
        //set a header test to DataGridView Image Column
        dgvImage.HeaderText = "Images";
        dgvImage.ImageLayout = DataGridViewImageCellLayout.Stretch;

        DataGridViewTextBoxColumn dgvId = new DataGridViewTextBoxColumn();
        dgvId.HeaderText = "ID";

        DataGridViewTextBoxColumn dgvName = new DataGridViewTextBoxColumn();
        dgvName.HeaderText = "Name";
        dataGridView1.Columns.Add(dgvId);
        dataGridView1.Columns.Add(dgvName);
        dataGridView1.Columns.Add(dgvImage);
        dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dataGridView1.RowTemplate.Height = 120;
        dataGridView1.AllowUserToAddRows = false;
    }

    // button add data to dataGridView
    // insert image from pictureBox to dataGridView 
    private void btn_Add_Click(object sender, EventArgs e)
    {
        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
        byte[] img = ms.ToArray();
        dataGridView1.Rows.Add(txt_UserID.Text, txt_Name.Text, img);
    }

    // browse image in pictureBox1 Click
    private void pictureBox1_Click(object sender, EventArgs e)
    {
        OpenFileDialog opf = new OpenFileDialog();
        opf.Filter = "Choose Image(*.jpg; *.png; *.gif)|*.jpg; *.png; *.gif";
        if (opf.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Image = Image.FromFile(opf.FileName);
        }
    }

    private void btn_Save_Click(object sender, EventArgs e)
    {
        for (int i = 5; i < dataGridView1.Rows.Count; i++)
        {
            string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
            string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();

            string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";

            this.getcom(insert_sql);
        }

        MessageBox.Show("Record Added");
    }

    public SqlConnection GetSqlConnection() //connection function
    {
        string str_sqlcon = "Data Source=DELL-PC;Initial Catalog=Image_DB;Integrated Security=True";

        SqlConnection mycon = new SqlConnection(str_sqlcon);
        mycon.Open();

        return mycon;
    }

    public void getcom(string sqlstr) //function for adding rows
    {
        SqlConnection sqlcon = this.GetSqlConnection(); // Watch out same string type as GetSQLConnection function
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcom.ExecuteNonQuery();
        sqlcom.Dispose();
        sqlcon.Close();
        sqlcon.Dispose();
    }
like image 476
Sumi Avatar asked May 16 '15 15:05

Sumi


Video Answer


2 Answers

The problem is within this " for " loop, you are not using the i in your for loop.

better try this one.

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
    string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString();
    string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString();
    string insert_sql = "INSERT INTO Input(UserID, UserName, PassImage) VALUES ('" + col1 + "','" + col2 + "','" + col3 + "')";
    this.getcom(insert_sql);
}
                                             

change the code logic, if needed.

like image 165
Balaji Avatar answered Sep 21 '22 00:09

Balaji


for (int i = 5; i < dataGridView1.Rows.Count; i++)

change this to for (int i = 0; i < dataGridView1.Rows.Count; i++)

You are assigning 5 to i so after one insert it will come out of the loop because i will become 6.

also include 'i' while specifying the datagridview row..else it will always point to one row and insert 5 rows but of same value

like image 31
Sachu Avatar answered Sep 20 '22 00:09

Sachu