How can i change this code for WPF Datagrid

John Bairlis 21 Reputation points
2021-02-04T11:52:40.627+00:00

Hi guys
I made this code for win forms datatgridview.
I want to use it in WPF Datagrid but in WPF Datagrid i can't use datagridview.Rows.Add.
Can someone help please

Private Sub fill_plan()
EmployeeGridView.Rows.Clear()
Try Dim i As Integer = 0
con.Open()
Dim query As String = "SELECT UnitID,Unit,Udate,State FROM Units where Month(Udate) =" & cmbMonth.SelectedIndex + 1 & ""
cmd = New SqlCommand(query, con)
myDR = cmd.ExecuteReader If myDR.HasRows Then While myDR.Read
EmployeeGridView.Rows.Add()
EmployeeGridView.Rows(i).Cells(0).Value = myDR.GetInt32(myDR.GetOrdinal("UnitID"))
EmployeeGridView.Rows(i).Cells(1).Value = myDR.GetString(myDR.GetOrdinal("Unit"))
Dim myday As Integer = DatePart(DateInterval.Day, myDR.GetValue(myDR.GetOrdinal("Udate")))
EmployeeGridView.Rows(i).Cells(myday + 1).Value = myDR.GetInt32(myDR.GetOrdinal("State"))
i = i + 1
End While
End If
myDR.Close()
con.Close()
Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Critical, "Σφάλμα")
End Try
End Sub

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,755 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
821 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,326 Reputation points
    2021-02-04T14:25:22.217+00:00

    Hi,
    try following demo:

    XAML:

    <Window x:Class="Window076"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp1"  
            mc:Ignorable="d"  
            Title="MainWindow" Height="450" Width="800">  
      <StackPanel>  
        <Button Content="Create demo data" Click="Button_Click"/>  
        <Button Content="Load and show demo data" Click="Button_Click_1"/>  
        <ComboBox x:Name="cmbMonth">  
          <ComboBoxItem>Jan</ComboBoxItem>  
          <ComboBoxItem>Feb</ComboBoxItem>  
          <ComboBoxItem>Mar</ComboBoxItem>  
        </ComboBox>  
        <DataGrid x:Name="EmployeeGridView" AutoGenerateColumns="False" Height="300"/>  
      </StackPanel>  
    </Window>  
    

    CodeBehind:

    Imports System.Collections.ObjectModel  
    Imports System.Data  
    Imports System.Data.SqlClient  
      
    Public Class Window076  
      Private Sub Button_Click(sender As Object, e As RoutedEventArgs)  
        CreateDemoData()  
      End Sub  
      
      Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)  
        fill_plan()  
        AddColumns()  
        Me.EmployeeGridView.ItemsSource = cvs.View  
      End Sub  
      
      Private cvs As New CollectionViewSource  
      Private col As New ObservableCollection(Of Data)  
      
      Private con As New SqlConnection(My.Settings.cnSqlServer)  
      Private cmd As SqlCommand  
      Private myDR As SqlDataReader  
      Private Sub fill_plan()  
        col.Clear()  
        Try  
          Dim i As Integer = 0  
          con.Open()  
          Dim query As String = "SELECT [UnitID],[Unit],[Udate],[State] FROM [Units] where Month(Udate) = @Month"  
          cmd = New SqlCommand(query, con)  
          cmd.Parameters.AddWithValue("@Month", cmbMonth.SelectedIndex + 1)  
          myDR = cmd.ExecuteReader  
          While myDR.Read  
            Dim d As New Data  
            d.UnitID = myDR.GetInt32(myDR.GetOrdinal("UnitID"))  
            d.Unit = myDR.GetString(myDR.GetOrdinal("Unit"))  
            Dim myday As Integer = CType(myDR.GetValue(myDR.GetOrdinal("Udate")), Date).Day  
            d.State(myday) = myDR.GetInt32(myDR.GetOrdinal("State"))  
            i = i + 1  
            col.Add(d)  
          End While  
          myDR.Close()  
          con.Close()  
          cvs.Source = col  
        Catch ex As Exception  
          MsgBox(ex.Message, MsgBoxStyle.Critical, "Σφάλμα")  
        End Try  
      End Sub  
      
      Private Sub AddColumns()  
        With Me.EmployeeGridView.Columns  
          .Clear()  
          .Add(New DataGridTextColumn With {.Header = "UnitID", .Binding = New Binding("UnitID")})  
          .Add(New DataGridTextColumn With {.Header = "Unit", .Binding = New Binding("Unit")})  
          For i = 1 To 31  
            .Add(New DataGridTextColumn With {.Header = $"{i}.", .Binding = New Binding($"State[{i}]")})  
          Next  
        End With  
      End Sub  
      
      Private Sub CreateDemoData()  
        Try  
          con.Open()  
          Dim query As String = "DROP TABLE IF EXISTS Units; CREATE Table Units([UnitID] Integer Identity, Unit NVarchar(255), Udate DateTime, State Integer, CONSTRAINT [PK_Units] PRIMARY KEY ([UnitID]));"  
          cmd = New SqlCommand(query, con)  
          cmd.ExecuteNonQuery()  
          cmd.CommandText = "INSERT [Units]([Unit],[Udate],[State]) VALUES(@unit,@udate,@state);"  
          cmd.Parameters.Add("@unit", SqlDbType.NVarChar, 255)  
          cmd.Parameters.Add("@udate", SqlDbType.DateTime)  
          cmd.Parameters.Add("@state", SqlDbType.Int)  
          Dim rnd As New Random  
          For i = 1 To 1000  
            cmd.Parameters("@unit").Value = $"Unit {i}"  
            cmd.Parameters("@udate").Value = New DateTime(2020, 1, 1).AddDays(rnd.Next(0, 100))  
            cmd.Parameters("@state").Value = rnd.Next(1, 1000)  
            cmd.ExecuteNonQuery()  
          Next  
          con.Close()  
        Catch ex As Exception  
          MsgBox(ex.Message, MsgBoxStyle.Critical, "Σφάλμα")  
        End Try  
      End Sub  
      
      Public Class Data  
        Public Property UnitID As Integer  
        Public Property Unit As String  
        Public Property State(dayIndex As Integer) As Integer  
          Get  
            Return days(dayIndex)  
          End Get  
          Set(value As Integer)  
            days(dayIndex) = value  
          End Set  
        End Property  
        Private days(31) As Integer  
      End Class  
      
    End Class  
    

    Result:

    63999-x.png

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.