首页 > 解决方案 > 在 TextBox WPF 中传递短日期

问题描述

您好,我有一个dataGrid双击打开一个新的Window并填充一些TextBoxes 我的问题是Textboxes显示日期和时间,我希望它显示短日期。

我已将我的 SQL Server 数据库配置为严格Date,它在数据库中显示短日期,所以我不确定它为什么DateTime在我的Textbox.

请帮忙!

这是我的窗口 1 代码:

        private void dtGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {

        // User double clicks on DataGrid Row
        // Open new Window
        // Populate selected textboxes with selected datarow
        DataGrid gd = (DataGrid)sender;
        DataRowView row_selected = gd.SelectedItem as DataRowView;

        var windowToOpen = new Window1();

        if (gd != null)
        {
            // Textboxes
            windowToOpen.txt_RowRecrd.Text = row_selected["DSP_ID"].ToString();
            windowToOpen.txt_DateResolved.Text = row_selected["DATERSLVD"].ToString();
            windowToOpen.txt_revcls.Text = row_selected["RateType"].ToString();

            windowToOpen.Show();
       }
    }

这是我TextBoxes在 Window 2 中的一个的 XAML:

                        <TextBox
                        x:Name="txt_DateResolved"
                        Width="110"
                        Height="26"
                        Margin="5,0,0,0"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Bottom"
                        Background="Transparent"
                        BorderBrush="Transparent"
                        BorderThickness="0"
                        Foreground="Black"
                        IsEnabled="True">
                    </TextBox>

标签: c#sqlwpfdatetimetextbox

解决方案


因为在 C# 中你没有Datestruct 你只有DateTimestructToString()在您的情况下,您可以在方法中格式化 DateTime 。您应该有一个 DateTime 的实例,并且可以在其上调用以下方法:

dateTime.ToShortDateString()

或者

dateTime.ToString("dd-MM-yy")

例子:

if (row_selected["DATERSLVD"] != null)
{   
  DateTime dateTime;
  if (DateTime.TryParse(row_selected["DATERSLVD"].ToString(), out dateTime))
  {
      windowToOpen.txt_DateResolved.Text = dateTime.ToShortDateString();
  }
  else
  {
      windowToOpen.txt_DateResolved.Text = ""; //assign default value
  }
}

推荐阅读