C# 错误问题(当前名称在中不存在)

C# 错误问题(当前名称在中不存在),c#,sql-server,crud,void-pointers,sqlcommand,C#,Sql Server,Crud,Void Pointers,Sqlcommand,我在新的sqlcommand查询中遇到错误。请帮我解决这个问题。如果不看到实际错误,很难确定,但我猜您的连接可能有问题con在btnSave\u单击中定义,但在BindData中不可访问。您需要将连接对象作为参数传递到该方法中。或者更好的是,生成一个新的连接,因为传递连接对象可能会产生许多其他问题 void BindData(SqlConnection-con)或 private void btnSave_Click(object sender, EventArgs e) {

我在新的sqlcommand查询中遇到错误。请帮我解决这个问题。

如果不看到实际错误,很难确定,但我猜您的连接可能有问题
con
btnSave\u单击中定义,但在
BindData
中不可访问。您需要将连接对象作为参数传递到该方法中。或者更好的是,生成一个新的连接,因为传递连接对象可能会产生许多其他问题

void BindData(SqlConnection-con)

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;
}

*注意:如上所述,当前状态下的代码极易受到sql注入攻击和其他安全问题的攻击。绝对不要以纯文本形式存储数据库连接信息,并对查询的所有输入进行参数化。

这不会解决您的问题,但这是sql注入的最佳选择。你需要参数化你的数据。也是纯文本密码的完美选择。而且对重新排序的列也很脆弱。并且也不保证处理SqlCommand、SqlConnection和SqlDataAdapter。要启动,显示一个连接仍处于打开状态的MessageBox。请发布完整的异常消息,它发生在哪一行?也属于“插入后从db进行完全刷新”反模式是的,连接“con”的问题。@ZeeshanIsmail如果此答案对您有帮助,请花一秒钟将其标记为解决方案:)谢谢!
void BindData()
{
    SqlConnection con = //Generate connection here
    ...
}