关于获取数据库值得WebService
public class EmployeeService : System.Web.Services.WebService
{
[WebMethod]
public Acct[] GetEmployeeList()
{
string connectionString = ConfigurationManager.ConnectionStrings[ "connectionNorthwind "].ToString();
string commandString = "select EmployeeID,LastName,FirstName from Employees ";
SqlConnection conn=new SqlConnection(connectionString);
SqlDataAdapter adapter=new SqlDataAdapter(commandString,conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
Acct[] a = new Acct[ds.Tables[0].Rows.Count];
Acct aa = new Acct();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
aa.EmployeeID =Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
aa.LastName = ds.Tables[0].Rows[i][1].ToString();
aa.FirstName = ds.Tables[0].Rows[i][2].ToString();
a[i] = aa;
}
return a;
}
}
[XmlRoot( "employee ")]
public class Acct
{
[XmlElement( "employeeID ")]
public int EmployeeID;
[XmlElement( "lastName ")]
public string LastName;
[XmlElement( "firstName ")]
public string FirstName;
}
用上面的方法不会出错(页面能显示xml数据),但是
Acct[] a = new Acct[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
a[i].EmployeeID =Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
a[i].LastName = ds.Tables[0].Rows[i][1].ToString();
a[i].FirstName = ds.Tables[0].Rows[i][2].ToString();
}
return a;
当运行到a[i].EmployeeID =Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());就会出错(页面不显示xml数据)。
那位高手能够告诉我错误的原因吗?
[解决办法]
Acct[] a = new Acct[ds.Tables[0].Rows.Count];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
a[i] = new Acct();//-------------------------加入此句试下?---------------------------------
a[i].EmployeeID =Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
a[i].LastName = ds.Tables[0].Rows[i][1].ToString();
a[i].FirstName = ds.Tables[0].Rows[i][2].ToString();
}
return a;