C# 需要从SQL Server中的另一个表访问用户名

C# 需要从SQL Server中的另一个表访问用户名,c#,sql,sql-server,winforms,C#,Sql,Sql Server,Winforms,数据库中有两个表,一个是UserAuth,另一个是CarAdd,但我需要在我的CarAdddataGridView1部分的UserAuth表中显示UserName 此方法显示我的CarAdd表中的所有数据: void Bindata() { SqlCommand cmd = new SqlCommand("select * from CarAdd", con); SqlDataAdapter sd = new SqlDataAdapter(cm

数据库中有两个表,一个是
UserAuth
,另一个是
CarAdd
,但我需要在我的
CarAdd
dataGridView1部分的
UserAuth
表中显示
UserName

此方法显示我的
CarAdd
表中的所有数据:

void Bindata()
{
        SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
        SqlDataAdapter sd = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sd.Fill(dt);

        dataGridView1.ItemsSource = dt.DefaultView;
}
但是,现在我需要在dataGridView1部分中显示
UserAuth
表中的用户名

我尝试过以下代码:

void BindataUserName()
{
        SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
        SqlDataAdapter sd = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sd.Fill(dt);

        // dataGridView1.ItemsSource = dt.DefaultView;
}
这是我的保存单击按钮,实际上我需要在单击此按钮后在dataGridView1上保存并显示用户名:

private void save_Click(object sender, RoutedEventArgs e)
{
        if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
        {
            try
            {
                con.Open();

                string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";

                SqlCommand cmd = new SqlCommand(newcon, con);
                cmd.ExecuteNonQuery();

                MessageBox.Show("Successfully inserted");
                Bindata();
                // TimeShow();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                 con.Close();
            }
        }
        else
        {
            MessageBox.Show("Invalid credentials");
        }
}
注意:我已为此项目创建了一个WPF Windows应用程序


谢谢大家!

由于
UserName
UserAuth
表中的一个属性,因此必须相应地修改SQL查询以获取它

SELECT UserName
FROM UserAuth
因此,对于
Bindatausername()
方法,应将
SqlCommand
更改为以下内容:

void BindataUserName()
{
        SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);

-您不应该将SQL语句连接在一起-而是使用参数化查询来避免SQL注入-签出ok,那么如何从数据库UserAuth表中显示带有“Lebel”的用户名!您可以通过将查询修改为下面的查询来查询
用户名
,即“Lebel”
SqlCommand cmd=newsqlcommand(“从UserAuth中选择用户名,其中UserName='Lebel'”,con)