为什么我的datagridview没有显示我插入的新行? [英] Why does my datagridview doesn't show me the new row inserted?

查看:88
本文介绍了为什么我的datagridview没有显示我插入的新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我在使用我的datagridview时遇到了一些困难。我正在使用MVVM构建一个WPF应用程序,我首先使用数据库。我有一个datagridview,它的itemsource绑定到一个Observable集合。现在,我我有点困惑,因为它绑定到表的itemsource,即使我手动设置其他列,列也会自动显示。所以我决定手动列必须去,但问题是我有一个文本框,其中一个插入serial nr。当插入serial nr时,行必须出现在datagridview中,将根据textbox中的serial nr获取整个数据。现在我正在使用RFID阅读器,我的函数由EnterKeyHelper获取自动进入行的类。我的datagridview的问题是:一,当我刷卡时没有出现行,第二行与第一行一起出现,说没有提供参数SN。现在,我有这样的问题,我发布了类似的问题,但不是相关问题是我的datagridview,但只是查询将行插入表AttendanceList。

这是我的Model类AttendanceList.cs:

 public partial class AttendanceList 
{
public int sNr {get;组; }
public string SN {get;组; }
public string fName {get;组; }
public string lName {get;组; }
public byte [] dateArrival {get;组; }
public System.DateTime dateDeparture {get;组; }
public double hoursSpent {get;组; }

//公共虚拟RegisterStudent RegisterStudent {get;组; }
}



ObservableCollection以及将数据插入AttendanceList的函数:

 private ObservableCollection< AttendanceList> list = new ObservableCollection< AttendanceList>(); 
public ObservableCollection< AttendanceList>项目
{
获得
{
返回列表;

}
设定
{
list = value;
NotifyPropertyChanged(Items);
}



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

SqlConnection conn = new SqlConnection(@Data Source =(LocalDB)\ MSSQLLocalDB; AttachDbFilename = C:\ Users \ user0909 \ Files \AndndanceListStudents.mdf ; Integrated Security = True; Connect Timeout = 30);
尝试
{
conn.Open();
SqlCommand cmd = new SqlCommand(插入AttendanceList(sNr,SN,fName,lName,dateArrival)从RegisterStudent中选择sNr,SN,fName,lName,getdate()作为dateArrival,其中SN = @ SN,conn) ;


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

int rowsAffected = cmd.ExecuteNonQuery();


//使用(AttendanceListStudentsEntities db = new AttendanceListStudentsEntities())
// {

// var q =(来自db中的数据)。 RegisterStudents
//其中data.SN == SerialN
//选择新的
// {
// SerialN = data.SN,
// studentNr = data .sNr,
// firstName = data.fName,
// lastName = data.lName
//}}。ToList()。选择(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。

这是我在视图中的绑定:

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)
{

}
}



和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 =AttendanceListHeight = 760宽度=800>
< Window.DataContext>
< local:AttendanceListViewModel />
< /Window.DataContext>
< Grid Background =#2e3137>
< TextBox Horizo​​ntalAlignment =LeftHeight =31Margin =171,212,0,0TextWrapping =WrapText ={Binding FilterString}VerticalAlignment =TopWidth =334/ >
< Button Content =SearchHorizo​​ntalAlignment =LeftMargin =569,197,0,0VerticalAlignment =TopWidth =104Height =47/>
< DataGrid Horizo​​ntalAlignment =LeftItemsSource ={Binding Items}Name =grdStudentsHeight =433Margin =0,287,0,0VerticalAlignment =TopWidth =792> ;
< DataGrid.Columns>

<! - < DataGridTextColumn Binding ={Binding SNr}Width =100Header =Serial no。 />
< DataGridTextColumn Binding ={Binding StudentNR}Width =100Header =Student no。/>
< DataGridTextColumn Binding ={Binding FullName}Width =100Header =Name/>
< DataGridTextColumn Binding ={Binding StartDate,StringFormat = \ {0:dd.MM.yy HH:mm:ss \}}Width =100Header =Arrival time/>
< DataGridTextColumn Binding ={Binding DepartureTime,StringFormat = \ {0:dd.MM.yy HH:mm:ss \}}Width =100Header =Departure time/>
< DataGridTextColumn Binding ={Binding HoursSpent,StringFormat = \ {0:HH:mm\}}Width =100Header =Total hours/> - >
< DataGridTemplateColumn Header =Edit Row>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< Button Name =editBtnContent =EditClick =editBtn_Click/>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< DataGridTemplateColumn Header =Delete Row>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< Button Content =DeleteName =deleteBtnCommand ={Binding Path = DeleteCommand}Click =deleteBtn_Click/>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< /DataGrid.Columns>
< / DataGrid>
< Button Content =Add studentCommand ={Binding Path = AddStudent}Horizo​​ntalAlignment =LeftMargin =25,119,0,0VerticalAlignment =TopWidth =83Height = 36\" />
< DatePicker Horizo​​ntalAlignment =LeftMargin =0,10,0,0VerticalAlignment =TopHeight =37Width =108/>
< Button Content =ReportHorizo​​ntalAlignment =LeftMargin =152,119,0,0VerticalAlignment =TopWidth =80Height =36/>
<按钮内容=更新出勤列表Click =Button_ClickHorizo​​ntalAlignment =LeftVerticalAlignment =TopWidth =139Margin =258,119,0,0Height =36RenderTransformOrigin = 0.407,0.884/>
< Button Content =CancelIsCancel =TrueHorizo​​ntalAlignment =LeftMargin =14,202,0,0VerticalAlignment =TopWidth =94Height =42RenderTransformOrigin =0.408 ,1.49\" />
< TextBox Horizo​​ntalAlignment =LeftText ={Binding SNr}Name =txtBoxFocusss:EnterKeyHelpers.EnterKeyCommand ={Binding ShowStudents}Height =23Margin =277,259,0,0 TextWrapping =WrapVerticalAlignment =TopWidth =120/>
//这是采用Serial nr(或SN)的文本框

< Button Content =Insert into reportHorizo​​ntalAlignment =LeftMargin =430,119,0,0 VerticalAlignment =TopWidth =127Height =36RenderTransformOrigin = - 0.047,0.5/>

< / Grid>
< / Window>



如何以错误的方式解决问题,即没有提供SN参数的错误和数据网格将SN插入文本框textboxFocus()后显示行?提前谢谢! :)



我尝试了什么:



我试过了以下是GetStudentData函数,我得到了相同的结果:

 SqlConnection conn = new SqlConnection(@Data Source =(LocalDB)\ MSSQLLocalDB; AttachDbFilename = C:\ Users\user0909\Documents\AndndanceListStudents.mdf; Integrated Security = True; Connect Timeout = 30); 
尝试
{
conn.Open();
SqlCommand cmd = new SqlCommand(插入AttendanceList(sNr,SN,fName,lName,dateArrival)从RegisterStudent中选择sNr,SN,fName,lName,getdate()作为dateArrival,其中SN = @SN,conn) ;
cmd.Parameters.AddWithValue(@ SN,SerialN);来自运行时的RegisterStudent-value = null
cmd.Parameters.AddWithValue(@ sNr,studentNr); // RegisterStudent,value at runtime = 0
cmd.Parameters.AddWithValue(@ fName,firstName); //运行时的RegisterStudent-value = null
cmd.Parameters.AddWithValue(@ lName,lastName); / / RegisterStudent在运行时的值= null
cmd.Parameters.AddWithValue(@ dateArrival,dateT); //运行时的AttendanceList值=当前日/小时
//cmd.Parameters.AddWithValue(\"@dateDeparture ,离开);
//cmd.Parameters.AddWithValue(\"@hoursSpent,hoursSpent);
int rowsAffected = cmd.ExecuteNonQuery();
}



使用(AttendanceListStudentsEntities db = new AttendanceListStudentsEntities())
{

var q =(来自db.RegisterStudents
中的数据,其中data.SN == SerialN
选择新的
{
SerialN = data.SN,
studentNr = data.sNr ,
firstName = data.fName,
lastName = data.lName
})。ToList()。选择(c => new AttendanceList
{
sNr = c.studentNr,
SN = c.SerialN,

fName = c.firstName,
lName = c.lastName

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



对于View我试图在txtboxFocus上绑定datagridview中的elementname(这是获取序列nr的那个)当我有我的手动实现的列时,它工作。现在,当我绑定Items ObservableCollection时,列是自动生成的,并且不需要旧的那些。

解决方案

当你输入一个新的数据而不是它插入但我永远不会显示,直到你的显示gridview更新所以你需要在每次插入后调用显示数据方法,这样每次插入后你的gridview将更新数据并显示新插入行。

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.

解决方案

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.


这篇关于为什么我的datagridview没有显示我插入的新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆