'How to add values from sql database to datagrid wpf [closed]
Dim connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\attendencerecordtest2\attendencerecordtest2\newdatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim cmd As New SqlCommand()
connection.Open()
cmd = New SqlCommand("select ID,Name from datatest1)", connection)
Dim dataadp As SqlDataAdapter = New SqlDataAdapter()
Dim dt As DataTable = New DataTable("datatest1")
dataadp.Fill(dt)
dg.ItemsSource = dt.DefaultView
dataadp.Update(dt)
cmd.ExecuteNonQuery()
connection.Close()
End Sub
<DataGrid x:Name="dg" HorizontalAlignment="Left" Height="227" Margin="295,123,0,0" VerticalAlignment="Top" Width="408" />
I am not able to get data from database into wpf datagrid. Above code Showing error at dataadp.fill(dt). Thanks
Solution 1:[1]
Let's look at your code.
Dim cmd As New SqlCommand()
That declares a variable, creates a SqlCommand object and assigns that object to the variable.
cmd = New SqlCommand("select ID,Name from datatest1)", connection)
That creates a another SqlCommand object, this time with a query and a connection, and assigns it to the same variable. What was the first command object for if you're just going to throw it away and use a second one?
Dim dataadp As SqlDataAdapter = New SqlDataAdapter()
That creates a new SqlDataAdapter that has no link whatsoever with either of the commands you created.
Only create a new object when you need a new object. If you don't want to create a new object, don't use the New keyword. Create one command, then create a data adapter with that command:
Dim command As New SqlCommand("select ID,Name from datatest1", connection)
Dim adapter As New SqlDataAdapter(command)
Better still, don't create the command at all and let the data adapter create it for you. Even better still, don't create the connection either. Just assign your connection string to a variable and then create a data adapter and let it do the rest:
Dim table As New DataTable
Using adapter As New SqlDataAdapter("SQL query here", connectionString)
adapter.Fill(table)
End Using
Done! No opening or closing the connection - the Fill method does that for you, as does the Update method when saving. No muss, no fuss.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John |
