Click here to Skip to main content
15,888,031 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello dears..
im trying to retrieve data from sql through class but it comes out empty mean no data return?

and is this is good way to retrieve ?
C#
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";
                person ps = new person();
                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);
                        //cmd.ExecuteNonQuery();
                        using (SqlDataReader sqld = cmd.ExecuteReader())
                        {
                            while(sqld.Read())
                            {
                                ps.name = sqld.GetString(0);
                                ps.sex = sqld.GetString(1);
                            }
                          }
                      }
                    }
                return ps;
            }
           
        }

in here i should get data for example if i write 1 in textbox1 i should get john name in textbox2 and male in textbox3 but its not retrieving any data without error...
C#
private void button1_Click(object sender, EventArgs e)
       {
           person x = new person();
           x.somemethod(Convert.ToInt32(textBox1.Text));   //  to select which data you want to retrieve
           textBox2.Text = x.name;//here its not showing data
           textBox3.Text = x.sex;//data not retrieve
       }


What I have tried:

the problem is its not giving any error !!! just no data retrieve.....
Posted
Updated 29-Oct-16 21:37pm
v2
Comments
[no name] 29-Oct-16 14:30pm    
"whats wrong", how would we know? We don't have access to your database. Learn how to debug your code.
jame01 29-Oct-16 14:34pm    
thanks for your care, as i mentioned i can't retrieve data , as it showing in button click event i should get data back to textbox2 and textbox3 but not getting it ....
thanks dear
[no name] 29-Oct-16 14:47pm    
As I said, learn how to debug your code. We don't have access to your database so we would have no idea why you can't.
You should debug and find out where exactly is the problem.
jame01 29-Oct-16 15:00pm    
sir im debugging it but no error shows up , the problem is no data comeback ...
thanks

Hi...just some coding suggestions

I think you should first organize the code better, so

The connection string (@"Data Source=~ \\dbtest;Integrated Security=True") should be stored in config file. Also you'd use the same connection string for every method and it's good to change from only one place
C#
public class Person
{
   //think of this as a Model - if you're using MVC
   public string name { get; set; }
   public string sex { get; set; }
}

public class DatabaseQueries
{
   //name your class whatever makes sense 

   public SqlConnection SqlConnection { get; set; }

   public DatabaseQueries()
   { 
       this.SqlConnection = new SqlConnection("get the connection string...");
   }

   public Person GetPerson(int IDNum)
   {
       Person person = null;
       try
       {
           //relevant code from somemethod to get person from database
           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();

           //use while when you expect multiple records, in this case only 1 seems expected so if can be used
           if(sqld.Read()) 
           {
              person = new Person();
              //set properties
              person.name = sqld.GetString(0);
              person.sex = sqld.GetString(1);
           }
           return person; //remember to check for null when retrieving person
       }
       catch (SqlException ex)
       {
           throw; //handle any errors
       }
       finally
       {
           SqlConnection.Close();                
       }
   }
}
 
Share this answer
 
v3
Comments
jame01 31-Oct-16 17:12pm    
thanks for your help...
i know this is good way to use it, but can you tell me what is wrong with this
private void button1_Click(object sender, EventArgs e)
{
DatabaseQueries dbs = new DatabaseQueries();//im calling class
dbs.GetPerson(Convert.ToInt32(textBox1.Text));//gaiving value
Person ps = new Person();
// Person settheperosn;
textBox2.Text =ps.name ;
textBox3.Text = ps.sex;

}
P_Z 1-Nov-16 14:35pm    
>> dbs.GetPerson(Convert.ToInt32(textBox1.Text));//gaiving value
>> Person ps = new Person(); //this person does Not have database details...just created a new object

Some minor updates to the button click
private void button1_Click(object sender, EventArgs e)
{
DatabaseQueries dbs = new DatabaseQueries();//im calling class
int personID = -1;
int.TryParse(textBox1.Text, out personID); //text may contain non digit chars
Person ps = dbs.GetPerson(personID); //Now person will be populated with database details
if (ps != null)
{
//null check due to person with personID may not exist
textBox2.Text = ps.name;
textBox3.Text = ps.sex;
}
}




Richard Deeming 1-Nov-16 15:04pm    
If you're just going to rethrow the exception, there's no point catching it. You might as well remove the catch (SqlException ex) { throw; } block. :)
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:
C#
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";
                // person ps = new person(); // this to be removed, you're already having an instance
                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);
                        //cmd.ExecuteNonQuery();
                        using (SqlDataReader sqld = cmd.ExecuteReader())
                        {
                            while(sqld.Read())
                            {
                                this.name = sqld.GetString(0); // use this.
                                this.sex = sqld.GetString(1); // use this.
                            }
                          }
                      }
                    }
                return this; // instead of returning the new instance return this
            }

The other option is to change the calling side so that you actually use the returned object, like this
C#
private void button1_Click(object sender, EventArgs e)
       {
           person x = new person();
           person returnedPerson;
           returnedPerson = x.somemethod(Convert.ToInt32(textBox1.Text));   //  to select which data you want to retrieve
           textBox2.Text = returnedPerson.name;//here its not showing data
           textBox3.Text = returnedPerson.sex;//data not retrieve
       }

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
C#
public static Person GetPerson(int IDNum)
   {
       Person person = null;
       try
       {
           //relevant code from somemethod to get person from database
           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();
 
           //use while when you expect multiple records, in this case only 1 seems expected so if can be used
           if(sqld.Read()) 
           {
              person = new Person();
              //set properties
              person.name = sqld.GetString(0);
              person.sex = sqld.GetString(1);
           }
           return person; //remember to check for null when retrieving person
       }
       catch (SqlException ex)
       {
           throw; //handle any errors
       }
       finally
       {
           SqlConnection.Close();                
       }
   }

and now the calling side would be
C#
private void button1_Click(object sender, EventArgs e)
       {
           person x;
           x = Person.GetPerson(Convert.ToInt32(textBox1.Text));   //  to select which data you want to retrieve
           textBox2.Text = x.name;//here its not showing data
           textBox3.Text = x.sex;//data not retrieve
       }
 
Share this answer
 
Comments
jame01 30-Oct-16 13:57pm    
that is really useful answer thanks so much for your precious time,
just wonder if this good or there other way i should learn,,,,,
many thanks again
Wendelius 30-Oct-16 15:08pm    
You're most welcome :)

There are a lot of different guidance and best practices but I believe that they are more like material from which to learn than exact instructions how to do something. So depending on the situation the best solution may vary a lot.

One thing that comes in mind is that you could separate the entity for the data from the logic how to fetch the data. One simple way could be just to split the person class to two partial classes. The other part would contain only the properties for storing the data while the other part would contain logic.
Wendelius 30-Oct-16 15:08pm    
You're most welcome :)

There are a lot of different guidance and best practices but I believe that they are more like material from which to learn than exact instructions how to do something. So depending on the situation the best solution may vary a lot.

One thing that comes in mind is that you could separate the entity for the data from the logic how to fetch the data. One simple way could be just to split the person class to two partial classes. The other part would contain only the properties for storing the data while the other part would contain logic.
jame01 20-Nov-16 15:59pm    
dear MR.Mika Wendelius
again thanks for your helps, you already helped me and it was so appreciated ,
here Im asking another favor if its not to much if its you already helped and that was enough :),
this is used for select can i use insert this way ?
its to different ?
Wendelius 23-Nov-16 9:21am    
If I understand the question correctly, yes you can use the same idea also with inserts. You could create a static method that executes the insert and gets the person as parameter. The signature would look something like

public static Person InsertPerson(Person personToInsert) {
....

However, it could make more sense not to make the method static. When you're fetching a person, you don't actually have the person thus having a static method id feasible. But when you insert a person you have already filled all the properties and you must pass the instance of the Person object for inserting. So why not define the insert as part of the person instance. In other words

class Person {
public bool Insert() {
... code to insert ...

In this case the call would be something like

Person person = new Person();
person.FirstName = "...";
person.LastName = "...";
...
if (!person.Insert()) {
... inform about a problem ...
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900