0

i've checked again and again , but couldn't find any error

private void Btn_Save_Click(object sender, EventArgs e)
    {

        SqlConnection c = new SqlConnection(conn);


                c.Open();
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    query = @"INSERT INTO '" + tbpg.Text + "' VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";

                }
        SqlCommand cmd = new SqlCommand(query,c);
        cmd.ExecuteNonQuery();
jarlh
  • 42,561
  • 8
  • 45
  • 63
  • you see there is not enough information to begin investigating this problem. all i can tell you is you cant connect to your table in database. maybe your connection string is wrong or table names? – Masoud Andalibi Apr 03 '17 at 09:45
  • 1
    Depending on the database system, to enclose a name you use different quotation characters. For example Sql Server uses the square brackets [tablename] while MySql uses backticks ` – Steve Apr 03 '17 at 09:47
  • " + tbpg.Text + " remove your single qouts – parvezalam khan Apr 03 '17 at 09:48
  • 2
    Remove single quotes around table name. BUT don't use this code please.. This is a bad practice... Please look at parameterized queries as this is SQL Injection susceptible – Gilad Green Apr 03 '17 at 09:48

2 Answers2

0

Try Below Code

query = @"INSERT INTO " + tbpg.Text + "  VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";
parvezalam khan
  • 480
  • 2
  • 11
0

With such a mass of string connactions, you need to output the final value of query during debugging. Otherwise you are basically guessing how it looks.

I did notice a difference in this line:

+ dgv.Rows[i].Cells["Date"].Value + ","

You are using i, rather then 0.

But generally building queries via string connaction is not a good idea. You should be use Parametized Queries. Otherwise you end up on the wrong side of this joke: https://xkcd.com/327/

Christopher
  • 9,634
  • 2
  • 17
  • 31