Alamin
Alamin

Reputation: 2165

Need access username from another table in SQL Server

I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.

This method shows all data from my CarAdd table:

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

But, now I need to show the username from the UserAuth table in the dataGridView1 section.

I have tried this code:

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

Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:

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

Note: I have created a WPF Windows application for this project

Thank you!

Upvotes: 0

Views: 185

Answers (1)

Paul
Paul

Reputation: 135

Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.

SELECT UserName
FROM UserAuth

So for the Bindatausername() method, the SqlCommand should be changed to the following:

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

Upvotes: 1

Related Questions