I've got two table as per diagram below and have some sample data on the table as well.
What I'm trying to achieve in my project is as follows. I've got 4 windows form in my project. First form with two buttons
New User
has a click event of-
private void button1_Click(object sender, EventArgs e)
{
NewUser nu = new NewUser();
nu.Show();
}
Upon click, it brings up NewUser form
The plan is to add data here for Users Table
then click Save and Proceed
(right now I'm using the default Save
button on NAV bar) which will take the UID
from Users Table
and add it under column UID
(which is foreign key in Address Table
) and open form FormAddress
where I can enter the data for the table.
Click event for Save and Proceed
is--
private void button1_Click(object sender, EventArgs e)
{
FormAddress ad = new FormAddress();
ad.Show();
getdata();
}
Upon research I've learned that I need to use SCOPE_IDENTITY
to get the value of UID
from last data insertion and carry it over to next form. So I've created a method getdata()
as follows and added it under button event Save and Proceed
The code I tried is
private void getdata()
{
SqlConnection sqlConnection1 = new SqlConnection(@"mycon string is here;" + "Initial Catalog=Stack;Integrated Security=YES");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Users";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
cmd.CommandText = "SCOPE_IDENTITY();";
sqlConnection1.Close();
}
I Just can't get my head to work and figure out how to get the SCOPE_IDENTITY
and make it work. Please ask me before I get down-voted. I'll respond and reply/make changes as necessary. And I have zipped the project and SQL server file HERE if anyone wants to download them to run and test. I've used SQL Server 2014 and Visual Studio 2013.