Почему мой datagridview не показывает мне новую вставленную строку?
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.
Это мой модельный класс 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; } }
ObservableCollection вместе с функцией для вставки данных в 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); } }
Теперь моя функция извлекает данные,но по какой-то причине она говорит, что я должен объявить параметр @SN.
Это моя привязка в представлении:
Смотреть.язык 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) { } }
и посмотреть.язык 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>
Как я могу решить эту проблему таким образом, чтобы ошибка, говорящая о том, что параметр SN не был указан, исчезла, а datagrid показал строку после того, как SN был вставлен в текстовое поле textboxFocus()?Заранее благодарю вас! :)
Что я уже пробовал:
Я попробовал следующее для функции GetStudentData и получил тот же результат:
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); }
Для представления я попытался привязать имя элемента в datagridview на txtboxFocus(который принимает последовательный nr), и это сработало, когда у меня были вручную реализованные столбцы.Теперь,когда я связал элементы ObservableCollection, столбцы были автоматически сгенерированы, и не было никакой необходимости в том, чтобы старые были там.