Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to batch record using windows form. But When I click button to save, it works very slowly especially in this code block. Do you have a solution?
C#
int i = 0;
    List<int> ChkedRow = new List<int>();

    if (dataGridView1.Rows.Count > 0)

        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["oid"].Value) == true)
            {
                ChkedRow.Add(i);
            }
        }
    if (ChkedRow.Count == 0)
    {
        MessageBox.Show("Geziye katılacak öğrenci seçiminde bulunmadınız!");
        return;
    }


What I have tried:

C#
private void button1_Click(object sender, EventArgs e)
{
    int i = 0;
    List<int> ChkedRow = new List<int>();

    if (dataGridView1.Rows.Count > 0)

        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["oid"].Value) == true)
            {
                ChkedRow.Add(i);
            }
        }
    if (ChkedRow.Count == 0)
    {
        MessageBox.Show("Geziye katılacak öğrenci seçiminde bulunmadınız!");
        return;
    }
    progressBar1.Visible = true;
    label5.Visible = true;
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.RunWorkerAsync();

    foreach (int j in ChkedRow)
    {
        try
        {
            var val1 = dataGridView1.Rows[j].Cells["tcno"].Value;
            var val2 = dataGridView1.Rows[j].Cells["ono"].Value;
            var val3 = dataGridView1.Rows[j].Cells["isim"].Value;
            var val4 = dataGridView1.Rows[j].Cells["soyisim"].Value;
            var val5 = dataGridView1.Rows[j].Cells["cinsiyet"].Value;
            var val6 = dataGridView1.Rows[j].Cells["dtarihi"].Value;
            var val7 = dataGridView1.Rows[j].Cells["sinifi"].Value;
            var val8 = dataGridView1.Rows[j].Cells["unvan"].Value;
            var val9 = dataGridView1.Rows[j].Cells["tel"].Value;
            var val10 = dataGridView1.Rows[j].Cells["vtel"].Value;
            var val11 = dataGridView1.Rows[j].Cells["kbaskani"].Value;

            using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = gezievrak2541.accdb; Jet OLEDB:Database Password = Fatih2541; Mode = ReadWrite"))
            {
                conn.Open();
                using (var cmd = new OleDbCommand("select * from gezilistemiz25 where adi = '" + val3 + "' and soyadi=  '" + val4 + "' ", conn))
                {
                    using (OleDbDataReader dr = cmd.ExecuteReader())
                    {
                        if (dr.Read())
                        {
                            while (dr.Read())
                            {
                                MessageBox.Show(" '" + val3 + " " + val4 + "' isimli öğrenciler veritabanında kayıtlıdır. Mükerrer kayıt yapılamaz. Lütfen kontrol ediniz.");
                            }
                        }
                        else
                        {
                            if (conn.State == ConnectionState.Closed)
                            {
                                conn.Open();
                            }

                            var cmdText = @"INSERT INTO  gezilistemiz25 (tcno,ono,adi,soyadi,cinsiyet,dtarihi,sinifi,unvani,tel,vtel,kbaskani) VALUES(@tcno,@ono,@adi,@soyadi,@cinsiyet,@dtarihi,@sinifi,@unvani,@tel,@vtel,@kbaskani)";
                            var komut = new OleDbCommand(cmdText, conn);

                            komut.Parameters.AddWithValue("@tcno", val1);
                            komut.Parameters.AddWithValue("@ono", val2);
                            komut.Parameters.AddWithValue("@isim", val3);
                            komut.Parameters.AddWithValue("@soyisim", val4);
                            komut.Parameters.AddWithValue("@sinifi", val5);
                            komut.Parameters.AddWithValue("@cinsiyet", val6);
                            komut.Parameters.AddWithValue("@unvan", val7);
                            komut.Parameters.AddWithValue("@dtarihi", val8);
                            komut.Parameters.AddWithValue("@tel", val9);
                            komut.Parameters.AddWithValue("@vtel", val10);
                            komut.Parameters.AddWithValue("@kbaskani", val11);
                            komut.ExecuteNonQuery();
                            komut.Dispose();
                            komut.Parameters.Clear();
                            conn.Close();
                            conn.Dispose();
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
   MessageBox.Show("Seçtiğiniz öğrenciler gezi listesine eklendi.");
}
Posted
Updated 3-Aug-23 19:14pm
v2
Comments
PIEBALDconsult 3-Aug-23 21:14pm    
Well, for one thing, don't keep instantiating and throwing away the connection and command.
Create each once, use them many times, then let them Dispose (use using statements) for them.
Also, don't use the Convert class when a cast will do.
Richard Deeming 4-Aug-23 4:04am    
"Slow" is the least of your problems!

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation/interpolation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Quote:
My code block works very slowly

Since 'slowly' is probably not the correct word, you need to define 'slowly'.
I guess that your code take a long time to complete.
since the offending part is rather short piece of code, one can suspect a huge amount of row to process. Because a fast piece of code processing millions of rows will take some time to complete, but this, we can't guess.
So how many records ?

Depending on how it is done, dynamic list resizing can turn ugly slow on huge lists.

In order to understand how your code spend time, it may be interesting to look at profiling.
Profiling (computer programming) - Wikipedia[^]
 
Share this answer
 
Comments
Member 12505620 4-Aug-23 1:39am    
I mean it takes a long time to save. It saves multiple lines each time. I know this will take a long time. However, that is a very long time. My progress bar is also not displayed when I click the button.
CPallini 4-Aug-23 2:37am    
5.
Patrice T 4-Aug-23 5:00am    
Thank you.
Try this and check the performance. There a few things hee that should help.

List<int> checkedRows = new List<int>();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (Convert.ToBoolean(row.Cells["oid"].Value))
    {
        checkedRows.Add(row.Index);
    }
}

if (checkedRows.Count == 0)
{
    MessageBox.Show("Geziye katılacak öğrenci seçiminde bulunmadınız!");
    return;
}
 
Share this answer
 
Comments
Member 12505620 3-Aug-23 23:49pm    
Thnaks for your intrest Eldon.
Member 12505620 4-Aug-23 4:10am    
Thanks for your intrest Eldon.
PIEBALDconsult 5-Aug-23 11:04am    
Don't use the Convert class when a cast will suffice.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900