[英]How to Populate a DataTable in a DataGridView
I've created a WCF Web service that returns a simple DataTable to a Windows form on Button Click.我创建了一个 WCF Web 服务,该服务在单击按钮时将简单的 DataTable 返回到 Windows 表单。 I'm having issues displaying the returned data in a DataGridView.我在 DataGridView 中显示返回的数据时遇到问题。
This is the code in the Web Service using VB这是Web服务中使用VB的代码
Public Function GetEmployees() As EmployeesData Implements IService1.GetEmployees
Dim str As New String("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|XXX.accdb;User Id=XXX;Password=XXX")
Dim conn As New OleDbConnection(str)
Dim cmd As New OleDbCommand("SELECT * FROM employees", conn)
conn.Open()
Dim sda = New OleDbDataAdapter
cmd.Connection = conn
sda.SelectCommand = cmd
Using dt As New DataTable()
Dim employees As New EmployeesData()
sda.Fill(employees.EmployeesTable)
Return employees
conn.Close()
End Using
End Function
<DataContract()>
Public Class EmployeesData
Public Sub New()
EmployeesTable = New DataTable("EmployeesData")
End Sub
<DataMember()>
Public Property EmployeesTable() As DataTable
End Class
And this is in the Windows form end on button click这是在 Windows 表单中单击按钮结束
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As Service1Client = New Service1Client()
DataGridView1.DataSource = client.GetEmployees()
DataGridView1.AutoGenerateColumns = True
End Sub
Now, when I click the button, It's not populating the data to the grid.现在,当我单击按钮时,它不会将数据填充到网格中。
Presumably this:大概是这样的:
DataGridView1.DataSource = client.GetEmployees()
should be this:应该是这样的:
DataGridView1.DataSource = client.GetEmployees().EmployeesTable
Your server code should look more like:您的服务器代码应该看起来更像:
Public Function GetEmployees() As EmployeesData Implements IEmployeesService.GetEmployees
Dim con As New String("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|XXX.accdb;User Id=XXX;Password=XXX")
Dim cmd = "SELECT * FROM employees"
Using sda As New OleDbDataAdapter(cmd, con)
Dim employees As New EmployeesData()
sda.Fill(employees.EmployeesTable)
End Using
End Function
And your client side code:和您的客户端代码:
Private Sub LoadEmployeesButton_Click(sender As Object, e As EventArgs) Handles LoadEmployeesButton.Click
Dim client = New EmployeesServiceClient()
EmployeesDataGridView.DataSource = client.GetEmployees().Employees
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.