6

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();
    }

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can u please tell, how can I restrict user to give input exactly 5 records otherwise a message will generated.
do the change in for loop, -> for(i=0;i<6;i++) so this will insert only 5 records. If you want to show message use datagridview client events or try the logic in if if(dataGridView1.Rows.count>5) .@Sumi
4
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.