UWP C#消除textbox.txt中的双逗号

时间:2017-02-16 00:09:58

标签: c# uwp

我的应用程序中有一个文本框,我希望用户能够输入字符串并按Enter键,这会将该字符串添加到变量并清除文本框。他们可以通过文本框向变量添加多个字符串,每个字符串用逗号分隔。但是当我将完整记录添加到我的csv文件时,它有双逗号。我无法看到它们的添加位置。

期望的结果 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();

我想我可以使用.replace()消除记录行中的双逗号,但我真的想了解我做错了导致问题的原因。

感谢您的任何意见!

编辑经过多一点测试后,每次按下键盘Enter时,似乎enter被点击两次。不知道为什么。

1 个答案:

答案 0 :(得分: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 = "";
        }
    }

}