Im trying to to get all of my table records using webservice. I tried this :
public class Student
{
public int id;
public string name;
public string grade;
}
[WebMethod]
public Student[] getall()
{
Student objStd = new Student();
Student[] stds = new Student[400];
SqlConnection conn;
conn = Class1.ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "select * from dbo.tblUser";
SqlDataReader sdr = newCmd.ExecuteReader();
for (int runs = 0; sdr.Read(); runs++)
{
objStd.id = Int32.Parse(sdr["Id"].ToString());
objStd.name = sdr["name"].ToString();
objStd.grade = sdr["grade"].ToString();
stds[runs] = objStd;
}
conn.Close();
sdr.Close();
return stds;
}
but the result of this is like this:
<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfStudent xmlns="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
-<Student>
<id>8</id>
<name>hhhhh</name>
<grade>76</grade>
</Student>
....
this will return only the last record again and again, why?
what should I correct in my code?
Make a List add to it and return, now you are returning only the last object.
Create the Student Object instance inside the For Loop
List<Student> stds = new List<Student>();
for (int runs = 0; sdr.Read(); runs++)
{
Student objStd = new Student();
objStd.id = Int32.Parse(sdr["Id"].ToString());
objStd.name = sdr["name"].ToString();
objStd.grade = sdr["grade"].ToString();
stds.Add(objStd);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With