Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,I'm having some struggle with my datagridview.I'm building an WPF application using MVVM,and I'm using database first.I have a datagridview which has its itemsource bound to an Observable collection.Now,I am a little confused because since it is bound to the itemsource of a table,the columns will automatically show even if i set other columns manually.So I decided the manual columns had to go,but he problem is that I have a textbox where a serial nr is inserted.When that serial nr is inserted,the row has to appear into the datagridview will the entire data fetched based on the serial nr in the textbox.Now I'm using an RFID reader and my function is taken by a EnterKeyHelper class that enters the row automatically.The problem with my datagridview is that:one,the rows do not appear when I swipe the card and the second comes hand in hand with the first,saying that the parameter SN was not supplied.Now,I had a problem like this and I have posted a similar issue,but not related to my datagridview,but only to the query to insert rows into the table AttendanceList.
This is my Model class AttendanceList.cs:
public partial class AttendanceList
   {
       public int sNr { get; set; }
       public string SN { get; set; }
       public string fName { get; set; }
       public string lName { get; set; }
       public byte[] dateArrival { get; set; }
       public System.DateTime dateDeparture { get; set; }
       public double hoursSpent { get; set; }

      // public virtual RegisterStudent RegisterStudent { get; set; }
   }

The ObservableCollection along with the function for inserting data into AttendanceList:
private ObservableCollection<AttendanceList> list=new ObservableCollection<AttendanceList>();
       public ObservableCollection<AttendanceList> Items
       {
           get
           {
               return list;

           }
           set
           {
               list = value;
               NotifyPropertyChanged("Items");
           }

public void GetStudentData(object param)
      {
          //try
          //{

          SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user0909\Documents\AttendanceListStudents.mdf;Integrated Security=True;Connect Timeout=30");
          try
          {
              conn.Open();
              SqlCommand cmd = new SqlCommand("insert into AttendanceList(sNr,SN,fName,lName,dateArrival) select sNr,SN,fName,lName,getdate() as dateArrival from RegisterStudent where SN =@SN", conn);


              cmd.Parameters.AddWithValue("@SN", SerialN);

              int rowsAffected = cmd.ExecuteNonQuery();


              //using (AttendanceListStudentsEntities db = new AttendanceListStudentsEntities())
              //{

              //    var q = (from data in db.RegisterStudents
              //             where data.SN == SerialN
              //             select new
              //             {
              //                SerialN = data.SN,
              //                 studentNr = data.sNr,
              //                 firstName = data.fName,
              //                 lastName = data.lName
              //             }).ToList().Select(c => new AttendanceList
              //             {
              //                 sNr = c.studentNr,
              //                 SN = c.SerialN,

              //                 fName = c.firstName,
              //                 lName = c.lastName

              //             }).ToList();
              //    Items = new ObservableCollection<AttendanceList>(q);
              //}


          }

          catch (Exception ex)
          {
              MessageBox.Show(ex.Message);
          }
      }

Now my function fetches the data but,for some reason it says that I have to declare the parameter @SN.
This is my binding in the view:
View.xaml.cs:
public partial class AttendanceList : Window
  {
      AttendanceListViewModel vm;

      public AttendanceList()
      {

          InitializeComponent();
          vm = new AttendanceListViewModel();
          this.DataContext = vm;
          txtBoxFocus.Focus();
          txtBoxFocus.Opacity = 0;
          grdStudents.Columns[6].Visibility = Visibility.Collapsed;
          grdStudents.Columns[7].Visibility = Visibility.Collapsed;
          vm.GetStudentData(grdStudents);

      }

      private void Button_Click(object sender, RoutedEventArgs e)
      {
          grdStudents.Columns[6].Visibility = Visibility.Visible;
          grdStudents.Columns[7].Visibility = Visibility.Visible;
      }

      private void editBtn_Click(object sender, RoutedEventArgs e)
      {
          grdStudents.IsReadOnly = false;
      }

      private void deleteBtn_Click(object sender, RoutedEventArgs e)
      {

      }
  }

and View.xaml:
<Window x:Class="WPFAttendanceApp.View.AttendanceList"
        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:WPFAttendanceApp.ViewModel"
        xmlns:ss="clr-namespace:WPFAttendanceApp.Helpers"
        mc:Ignorable="d"
        Title="AttendanceList" Height="760" Width="800">
    <Window.DataContext>
        <local:AttendanceListViewModel/>
    </Window.DataContext>
    <Grid Background="#2e3137">
        <TextBox HorizontalAlignment="Left" Height="31" Margin="171,212,0,0" TextWrapping="Wrap" Text="{Binding FilterString}" VerticalAlignment="Top" Width="334"/>
        <Button Content="Search" HorizontalAlignment="Left" Margin="569,197,0,0" VerticalAlignment="Top" Width="104" Height="47"/>
        <DataGrid  HorizontalAlignment="Left"  ItemsSource="{Binding Items}"  Name="grdStudents" Height="433" Margin="0,287,0,0" VerticalAlignment="Top" Width="792">
            <DataGrid.Columns>

                <!--<DataGridTextColumn Binding="{Binding SNr}" Width="100" Header="Serial no."  />
                <DataGridTextColumn Binding="{Binding StudentNR}" Width="100" Header="Student no."/>
                <DataGridTextColumn Binding="{Binding FullName}" Width="100" Header="Name"/>
                <DataGridTextColumn Binding="{Binding StartDate,StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" Width="100" Header="Arrival time"/>
                <DataGridTextColumn Binding="{Binding DepartureTime,StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" Width="100" Header="Departure time"/>
                <DataGridTextColumn Binding="{Binding HoursSpent,StringFormat=\{0:HH:mm\}}" Width="100" Header="Total hours"/>-->
                <DataGridTemplateColumn  Header="Edit Row">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="editBtn" Content="Edit" Click="editBtn_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Delete Row">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Name="deleteBtn" Command="{Binding Path=DeleteCommand}" Click="deleteBtn_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Add student" Command="{Binding Path=AddStudent}" HorizontalAlignment="Left" Margin="25,119,0,0" VerticalAlignment="Top" Width="83" Height="36"/>
        <DatePicker HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Height="37" Width="108"/>
        <Button Content="Report" HorizontalAlignment="Left" Margin="152,119,0,0" VerticalAlignment="Top" Width="80" Height="36"/>
        <Button Content="Update attendance list" Click="Button_Click" HorizontalAlignment="Left" VerticalAlignment="Top" Width="139" Margin="258,119,0,0" Height="36" RenderTransformOrigin="0.407,0.884"/>
        <Button Content="Cancel" IsCancel="True" HorizontalAlignment="Left" Margin="14,202,0,0" VerticalAlignment="Top" Width="94" Height="42" RenderTransformOrigin="0.408,1.49"/>
        <TextBox HorizontalAlignment="Left" Text="{Binding SNr}" Name="txtBoxFocus" ss:EnterKeyHelpers.EnterKeyCommand="{Binding ShowStudents}"  Height="23" Margin="277,259,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
//this is the textbox that takes the Serial nr (or SN)
      
  <Button Content="Insert into report" HorizontalAlignment="Left" Margin="430,119,0,0" VerticalAlignment="Top" Width="127" Height="36" RenderTransformOrigin="-0.047,0.5"/>

    </Grid>
</Window>

How can I solve the issue in such way that the error saying that the SN parameter not being supplied to be gone and the datagrid to show the row after the SN was inserted into the textbox textboxFocus()?Thank you in advance! :)

What I have tried:

I have tried the following for the GetStudentData function and I had the same result:
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user0909\Documents\AttendanceListStudents.mdf;Integrated Security=True;Connect Timeout=30");
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("insert into AttendanceList(sNr,SN,fName,lName,dateArrival) select sNr,SN,fName,lName, getdate() as dateArrival from RegisterStudent where SN = @SN", conn);
                cmd.Parameters.AddWithValue("@SN", SerialN);comes from RegisterStudent-value at runtime=null
            cmd.Parameters.AddWithValue("@sNr", studentNr);//RegisterStudent,value at runtime=0
            cmd.Parameters.AddWithValue("@fName", firstName);//RegisterStudent-value at runtime=null
                cmd.Parameters.AddWithValue("@lName", lastName) ;//RegisterStudent value at runtime =null
                cmd.Parameters.AddWithValue("@dateArrival", dateT);//AttendanceList value at runtime=currentday/hour
                //cmd.Parameters.AddWithValue("@dateDeparture", departure);
                //cmd.Parameters.AddWithValue("@hoursSpent", hoursSpent);
                int rowsAffected = cmd.ExecuteNonQuery();
            }

using (AttendanceListStudentsEntities db = new AttendanceListStudentsEntities())
              {

                 var q = (from data in db.RegisterStudents
                          where data.SN == SerialN
                          select new
                          {
                             SerialN = data.SN,
                             studentNr = data.sNr,
                              firstName = data.fName,
                              lastName = data.lName
                          }).ToList().Select(c => new AttendanceList
                          {
                             sNr = c.studentNr,
                               SN = c.SerialN,

                               fName = c.firstName,
                               lName = c.lastName

                           }).ToList();
                  Items = new ObservableCollection<AttendanceList>(q);
              }

For the View I have tried to bind the elementname in the datagridview on txtboxFocus(which is the one that takes the serial nr) and it worked when i had my manually implemented columns.Now when I binded the Items ObservableCollection,the columns were auto-generated and there was no need for the old ones to be there.
Posted
Updated 16-May-18 2:36am

1 solution

when you enter a new data than it is inserted but i will never show till your display gridview update so you need to call display data method after every insertion so that after every insertion your gridview will update data and show newly inserted row.
 
Share this answer
 
Comments
Daniel Andrei Popescu 16-May-18 14:35pm    
Thank you for your response.The thing is that I would like it to update every time a student swipes the card over the card reader,as the value(the serial nr) in the textbox is checked with the database.I binded to a dependancyproperty that automatically should insert the new row,it basically works like a button.Do you think it is possible to assign the function to it so that it will update automatically at every row inserted?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900