Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
First of all sorry for my bad English. I am new in the world of programming. I have so many doubts about c# and its back ends. I googled about c# datagridview and mysql, and i found some codes. then i generate them in my own way. there is a problem. if there is one row in datagrid view then two times the data get stored in db. and also if there is 2 then 3 times. and so on... i think the problem with my for loop section. i want to solve this. i dont know how to do that. please help me friends. here is the code below.


C#
private void cmdSaveOrPrint_Click(object sender, EventArgs e)
            {
                /* These commands check the mandatory fields, if there is a null value in the form and shows message box */
    
                if (txtCustomerName.Text == "" || txtAddress.Text == "" || txtPhoneNumber.Text == "" || Convert.ToString(dgNewSale.Rows[0].Cells["dgItemName"].Value) == string.Empty || Convert.ToString(dgNewSale.Rows[0].Cells["dgQuantity"].Value) == string.Empty)
                {
                    MessageBox.Show("Something Missing! Please Fill All The Required Sales Details", "Malabar Plywoods and Glass House", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
    
                /* These commands confirms that there are no null data in the mandatory fields and insert the data into the database */
    
                else if (txtCustomerName.Text != "" && txtAddress.Text != "" && txtPhoneNumber.Text != "" && Convert.ToString(dgNewSale.Rows[0].Cells["dgItemName"].Value) != string.Empty && Convert.ToString(dgNewSale.Rows[0].Cells["dgQuantity"].Value) != string.Empty)
                {
                    int counter;
                    for (counter = 0; counter < (dgNewSale.Rows.Count); counter++)
                    {
                        int i;
                        mdiManager mdiTempManager = new mdiManager();
                        string host = "datasource=localhost;port=3306;username=root;password=";
                        string mysqlQueryInsertInto = "INSERT INTO db_malabar.sales_info (invoice_number, customer_name, address, customer_phone_number, date_of_purchase, time_of_purchase, item_name, item_code, unit, quantity, retail_unit_price, discount, total_amount) VALUES('" + this.txtInvoiceNumber.Text + "', '" + this.txtCustomerName.Text + "', '" + this.txtAddress.Text + "', '" + txtPhoneNumber.Text + "', '" + lblDateDisplay.Text + "', '" + lblTimeDisplay.Text + "', '" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgItemName"].Value) + "','" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgItemCode"].Value) + "', '" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgUnit"].Value) + "', '" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgQuantity"].Value) + "', '" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgUnitPrice"].Value) + "', '" + txtDiscount.Text + "', '" + Convert.ToString(dgNewSale.Rows[counter].Cells["dgGrandTotal"].Value) + "') ;";
                        MySqlConnection rx = new MySqlConnection(host);
                        MySqlCommand condb = new MySqlCommand(mysqlQueryInsertInto, rx);
                        MySqlDataReader myReader;
                        
                        try
                        {
                            rx.Open();
                            myReader = condb.ExecuteReader();
                            for (i = 1; i <= 1; i++)
                            {
                                MessageBox.Show("Sales Details Saved Successfully. Click OK to Print", "Malabar Plywoods and Glass House", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            while (myReader.Read())
                            {
                            }
    
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        rx.Close();
                    }
                }
            }
Posted
Comments
Anand Gunasekaran 14-Mar-14 7:41am    
Hi, The Following Link may help to you..

http://www.dreamincode.net/forums/topic/238727-insert-update-and-delete-records-in-table-with-datagridview-using-c%23/

Thanks & Regards,
Anand. G

1 solution

well i am not sure how your code is working but may be you are doing a little wrong thing on some place. check your if and else if loop condition.....


you are comparing only first row i.e. row[0] for null or empty value. what if there is null or empty value for second / third row. it will still check for row[0] in your above case. so it would be better if you start for loop before the if and else if condition and check for each rows for null and empty value.
 
Share this answer
 
v2
Comments
d!l33p nair 14-Mar-14 8:44am    
tq for your reply. i am not perfect in c#. but i will try. tq. :)
d!l33p nair 14-Mar-14 8:57am    
hey buddy, i tried new codes, in new ways. it can insert multiple rows but, i got an error, which is "object reference not set to an instance of an object" here is the code... why this error happened?



private void cmdSave_Click(object sender, EventArgs e)
{
string config = "server=localhost; userid = root; database = db_malabar";
MySqlConnection con = new MySqlConnection(config);
string query = "INSERT INTO db_malabar.temp_sales_info(invoice_number, customer_name, address, customer_phone_number, date_of_purchase, time_of_purchase, item_code, item_name, unit, quantity, retail_unit_price, total_amount, discount, grand_total) VALUES (@invoice_number, @customer_name, @address, @customer_phone_number, @date_of_purchase, @time_of_purchase, @item_code, @item_name, @unit, @quantity, @retail_unit_price, @total_amount, @discount, @grand_total)";

MySqlCommand cmd = new MySqlCommand(query, con);
con.Open();
try
{
for (int row = 0; row < dgNewSale.Rows.Count; row++)
{

cmd.Parameters.AddWithValue(
"@invoice_number", txtInvoiceNumber.Text);
cmd.Parameters.AddWithValue(
"@customer_name", txtCustomerName.Text);
cmd.Parameters.AddWithValue(
"@address", txtAddress.Text);
cmd.Parameters.AddWithValue(
"@customer_phone_number", txtPhoneNumber.Text);
cmd.Parameters.AddWithValue(
"@date_of_purchase", lblDateDisplay.Text);
cmd.Parameters.AddWithValue(
"@time_of_purchase", lblTimeDisplay.Text);
cmd.Parameters.AddWithValue(
"@item_name", dgNewSale.Rows[row].Cells["dgItemName"].Value.ToString());
cmd.Parameters.AddWithValue(
"@item_code", dgNewSale.Rows[row].Cells["dgItemCode"].Value.ToString());
cmd.Parameters.AddWithValue(
"@unit", dgNewSale.Rows[row].Cells["dgUnit"].Value.ToString());
cmd.Parameters.AddWithValue(
"@quantity", dgNewSale.Rows[row].Cells["dgQuantity"].Value.ToString());
cmd.Parameters.AddWithValue(
"@retail_unit_price", dgNewSale.Rows[row].Cells["dgUnitPrice"].Value.ToString());
cmd.Parameters.AddWithValue(
"@total_amount", dgNewSale.Rows[row].Cells["dgAmount"].Value.ToString());
cmd.Parameters.AddWithValue(
"@discount", dgNewSale.Rows[row].Cells["dgDiscount"].Value.ToString());
cmd.Parameters.AddWithValue(
"@grand_total", dgNewSale.Rows[row].Cells["dgGrandTotal"].Value.ToString());


cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
MessageBox.Show("Success");
}
con.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
ravikhoda 14-Mar-14 9:02am    
difficult to say from above code. it may possible that in your datagrid some row may have null value which you are trying to pass in your database. please add a break point and try to debug your code and check on which line you are getting error.
d!l33p nair 14-Mar-14 9:11am    
tq for your reply.
the error line is...

cmd.Parameters.AddWithValue( "@item_name", dgNewSale.Rows[row].Cells["dgItemName"].Value.ToString());

till the end. i mean the all lines related to datagridview.
ravikhoda 14-Mar-14 9:26am    
ok now check for which row number you are getting this error specially check dgItemName value in the gridview and you may get your problem solved.

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