2017-02-16 33 views
0

我在我的应用程序中有一个文本框,我希望用户能够输入一个字符串并敲入回车,它将该字符串添加到变量并清除文本框。他们可以通过文本框向变量添加多个字符串,每个字符串之间用逗号分隔。但是当我将完整的记录添加到我的csv文件时,它有两个逗号。我看不到他们在哪里被添加。UWP C#从textbox.txt中消除双逗号

期望的结果 1/1/2017,12:00,乔,出,1234,09112,4545,120034

什么,现在我越来越 1/1/2017,12 :00,乔,出,1234,09112,4545,,120034 ,,

这里的相关代码:

 private void meterNumberBox_KeyDown(object sender, KeyRoutedEventArgs e) 
     { 
      if (e.Key == Windows.System.VirtualKey.Enter) 
      { 
       singlescan = meterNumberBox.Text + ","; 
       meternumber += singlescan; 
       meterNumberBox.Text = ""; 
       singlescan = ""; 

      } 
     } 


     private async void SubmitButton_Click(object sender, RoutedEventArgs e) 
     { 
      action = "out"; 

      // create record to be added to CSV 
      recordline = DateTime.Today.ToString("MM/dd/yyyy") + ","; 
      recordline += DateTime.Now.ToString("HH:mm:ss"); 
      recordline += ","; 
      recordline += checkoutName; 
      recordline += ","; 
      recordline += action; 
      recordline += meternumber; 
      recordline += "\r\n"; 

// then it submits the recordline to the record file. 
     // open csv and append record 
     StorageFolder appStoragefolder = ApplicationData.Current.RoamingFolder; 
     StorageFile appRecordFile = await appStoragefolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); // if it doesn't exist it will be created 
     var stream = await appRecordFile.OpenAsync(FileAccessMode.ReadWrite); 
     using (var outputstream = stream.GetOutputStreamAt(stream.Size)) 
     { 
      using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputstream)) 
      { 
       dataWriter.WriteString(recordline); 
       await dataWriter.StoreAsync(); 
       await outputstream.FlushAsync(); 
      } 
     } 

     stream.Dispose(); 

我想我可以消除来自recordline双逗号与.repl王牌(),但我真的很想明白我做错了导致问题。

感谢您的任何意见!

编辑:一点点更多的测试后,似乎enter被击中两次,每次在键盘按下回车键。不知道为什么。

+0

如果没有好的[mcve],就不可能提供具体建议的好答案。也就是说,根据你写的内容,看起来一切正常。您似乎正在使用使用双逗号来转义逗号的CSV实现(因为逗号分隔了文件中的一行内的字段)。只要你使用相同的CSV实现来读取文件,我希望它能正确解码转义的逗号。 –

+0

我编辑了我的问题,表明我只是将一个字符串添加到文本文件中,而不使用任何CSV处理方法。 – JayCee

+0

此外,这里没有任何东西可以防止用户在文本框为空时按Enter键,这会导致额外的逗号。不一定是现在发生的事情,而是需要注意的事情。 – dazedandconfused

回答

0

在意识到我需要搜索短语“UWP keydown事件两次发射”后,我发现了我的问题的答案。根据博客文章和帖子,这似乎是Windows 10 UWP应用程序中的一个错误。

http://blog.mzikmund.com/2015/12/winrt-keydown-fired-twice-when-enter-is-pressed/

Keydown Event fires twice

我能够加入到解决我的具体情况:

if (e.KeyStatus.RepeatCount == 1) 
{ 
    //Execute code 
} 

所以我最后的事件处理程序是这样的:

private async void meterNumberBox_KeyDown(object sender, KeyRoutedEventArgs e) 
{ 
    if (e.Key == Windows.System.VirtualKey.Enter) 
    { 
     if (e.KeyStatus.RepeatCount == 1) 
     { 
      singlescan = meterNumberBox.Text + ","; 
      meternumber += singlescan; 
      singlescan = ""; 
      meterNumberBox.Text = ""; 
     } 
    } 

}