It looks like you call the
GetPerson
of a person object but inside the code you instantiate a new person and fill the properties for that person. However, the newly instantiated person is never used.
So inside the
GetPerson
method, remove the
new Person
call and set the properties of the object at hand. In other words:
public class person
{
public string name { get; set; }
public string sex { get; set; }
public person somemethod(int IDnum)
{
string stselect = "select name,sex from tbltxt where ID=@ID";
using (SqlConnection cn = new SqlConnection(@"Data Source=~ \\dbtest;Integrated Security=True"))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand(stselect,cn))
{
cmd.Parameters.AddWithValue("@ID", IDnum);
using (SqlDataReader sqld = cmd.ExecuteReader())
{
while(sqld.Read())
{
this.name = sqld.GetString(0);
this.sex = sqld.GetString(1);
}
}
}
}
return this;
}
The other option is to change the calling side so that you actually use the returned object, like this
private void button1_Click(object sender, EventArgs e)
{
person x = new person();
person returnedPerson;
returnedPerson = x.somemethod(Convert.ToInt32(textBox1.Text));
textBox2.Text = returnedPerson.name;
textBox3.Text = returnedPerson.sex;
}
However, that would be a bit clumsy to first create a new object which again creates a new object. To tackle that you could define the
GetPerson
method as static. In that case the
GetPerson
would be
public static Person GetPerson(int IDNum)
{
Person person = null;
try
{
SqlConnection.Open();
SqlCommand cmd = SqlConnection.CreateCommand();
cmd.CommandText = @"select name,sex from tbltxt where ID = @ID";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", IDnum);
SqlDataReader sqld = cmd.ExecuteReader();
if(sqld.Read())
{
person = new Person();
person.name = sqld.GetString(0);
person.sex = sqld.GetString(1);
}
return person;
}
catch (SqlException ex)
{
throw;
}
finally
{
SqlConnection.Close();
}
}
and now the calling side would be
private void button1_Click(object sender, EventArgs e)
{
person x;
x = Person.GetPerson(Convert.ToInt32(textBox1.Text));
textBox2.Text = x.name;
textBox3.Text = x.sex;
}