Here I have created sample that inserts Gender into Database table using Form1 also gets Gender By Id on From2.
Code
Form1:
public Form1()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
this.SaveGender();
Form2 form2 = new Form2();
this.Hide();
form2.Show();
}
private void SaveGender()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Persons(Gender) VALUES(@Gender)", con))
{
string gender = rbtnMale.Checked ? "M" : "F";
cmd.Parameters.AddWithValue("@Gender", gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Form2
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.GetGender();
}
private void GetGender()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Gender FROM Persons WHERE PersonId = @PersonId", con))
{
cmd.Parameters.AddWithValue("PersonId", Convert.ToInt32(this.txtPersonId.Text));
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtGender = new DataTable();
sda.Fill(dtGender);
foreach (DataRow dr in dtGender.Rows)
{
if (dr["Gender"].ToString() == "M")
{
rbtnMale.Checked = true;
}
else
{
rbtnFemale.Checked = true;
}
}
}
}
}
}
Database
I have made use of the following table Persons with the schema as follows.
I have already inserted few records in the table.
You can download database SQL from here.
Download SQL