-2
private void btnSave_Click(object sender, EventArgs e)
{
           
    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=LoginDB;Integrated Security=True");
    con.Open();
    SqlCommand commamd = new SqlCommand("insert into tblUser values ('"+string.Format(txtUser.Text)+"' , '"+ txtServer.Text+"' , '"+txtpwd.Text+"', getdate())" ,con );
    commamd.ExecuteNonQuery();
    MessageBox.Show("Successfully Inserted");
    con.Close();
    BindData();
}

void BindData() 
{
    SqlCommand command = new SqlCommand("select * from tblUser" ,con);
    SqlDataAdapter sd = new SqlDataAdapter();
    DataTable dt = new DataTable();
    sd.Fill(dt);
    dataGridView.DataSource = dt;
}

I face error in new sqlcommand query. Please help me with this.

David L
  • 32,885
  • 8
  • 62
  • 93
  • 4
    It won't resolve your issue, but this is a perfect candidate for sql injection. You need to parameterize your data. – David L Dec 31 '20 at 05:04
  • Also a perfect candidate for plain-text passwords. And also fragile to columns being reordered. And also does not guarantee disposing of SqlCommand, SqlConnection and SqlDataAdapter. To boot, shows a MessageBox with the connection still open – Charlieface Dec 31 '20 at 05:07
  • Please post the full exception message, which line did it occur on? – Charlieface Dec 31 '20 at 05:08
  • Also falls into the "do a full refresh from the db after an insert" anti-pattern – Charlieface Dec 31 '20 at 05:10

1 Answers1

2

It's hard to know for sure without seeing the actual error, but my guess would be you are having an issue with your connection. con is defined in btnSave_Click but is not accessible in BindData. You'll need to pass the connection object into that method as a parameter. Or better yet, generate a new connection as passing connection objects around can create lots of other issues.

void BindData(SqlConnection con) or

void BindData()
{
    SqlConnection con = //Generate connection here
    ...
}

*Note: As mentioned in the comments above, your code in its current state is extremely vulnerable to sql injection attacks and other security issues. Definitely don't store database connection info in plain text and parameterize all the inputs to your query.

Wellerman
  • 846
  • 4
  • 14