要返回 DataTable,你可以在 Web 服务的方法中使用以下步骤:

  1. 创建一个 DataTable 对象,并定义表的列。例如,假设你要返回一个包含名称和年龄的 DataTable,可以这样定义:
DataTable table = new DataTable();
table.Columns.Add('Name', typeof(string));
table.Columns.Add('Age', typeof(int));
  1. 向 DataTable 中添加行数据。例如,假设你有一个包含多个人员信息的 List,可以通过循环将其添加到 DataTable 中:
List<Person> persons = GetPersons(); // 假设这是一个获取人员信息的方法
foreach (Person person in persons)
{
    DataRow row = table.NewRow();
    row['Name'] = person.Name;
    row['Age'] = person.Age;
    table.Rows.Add(row);
}
  1. 将 DataTable 作为 Web 服务方法的返回值:
[WebMethod]
public DataTable GetPersonData()
{
    DataTable table = new DataTable();
    // 添加列
    table.Columns.Add('Name', typeof(string));
    table.Columns.Add('Age', typeof(int));
    
    // 添加行
    List<Person> persons = GetPersons();
    foreach (Person person in persons)
    {
        DataRow row = table.NewRow();
        row['Name'] = person.Name;
        row['Age'] = person.Age;
        table.Rows.Add(row);
    }
    
    return table;
}

请注意,上述示例中的 Person 是一个自定义的类,用于表示人员信息。你可以根据实际情况进行调整。

C# Web Service 返回 DataTable 的方法详解

原文地址: https://www.cveoy.top/t/topic/mFTn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录