Zeeshan Ismail
Zeeshan Ismail

Reputation: 1

error problem(the current name doesn't exist in the )

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.

Upvotes: -2

Views: 50

Answers (1)

Wellerman
Wellerman

Reputation: 856

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.

Upvotes: 2

Related Questions