C# 在C和WPF中显示日期时间
我在第一个窗口中选择了一个DateTime变量,并试图在第二个窗口中显示。它按原样连接到数据库,但它显示的是来自数据库的随机数据,而不是所选数据。 代码如下:C# 在C和WPF中显示日期时间,c#,wpf,C#,Wpf,我在第一个窗口中选择了一个DateTime变量,并试图在第二个窗口中显示。它按原样连接到数据库,但它显示的是来自数据库的随机数据,而不是所选数据。 代码如下: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEvent
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Are you sure?");
Window1 win1 = new Window1();
win1.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
{
string connectionString = null;
SqlConnection cnn;
connectionString =
@"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True";
try
{
SqlConnection con =
new SqlConnection(
@"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into [Event] (Description,StartData,EndData,Type) values (@description,@startdata,@endata,@type)";
cmd.Parameters.AddWithValue("description", descriptionTxt.Text);
cmd.Parameters.AddWithValue("startData", StartDate.Value);
cmd.Parameters.AddWithValue("endata", EndDate.Value);
cmd.Parameters.AddWithValue("type", typeTxt.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
////Window2 win = new Window2(id);
//Window2 win3 = new Window2();
//this.Close();
//win3.Show();
SqlConnection conn =
new SqlConnection(
@"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
int query= Convert.ToInt32(comm.CommandText = "select MAX(StartData) from [Events]");
Window2 win = new Window2(query);
win.Show();
}
错误是输入字符串的格式不正确。如何转换它?在代码中有一些东西需要查看/考虑,首先是您的问题。 这行代码:
int query= Convert.ToDateTime(comm.CommandText = "select MAX(DateTime) from [Events]");
由于您没有执行代码,因此无法实现您所追求的目标。实际上,您正在尝试将命令对象转换为日期时间
在前面的方法中,您正在写入数据库,其中的一部分调用了以下命令:
cmd.ExecuteNonQuery
在command对象上还有各种其他方法,它们都以不同的方式工作。要了解这些方法,请访问本文,但基本上您可能希望使用ExecuteScalar方法来完成您正在尝试的操作
下一步,我会考虑将连接字符串移动到App.CONFIG文件,并从那里访问它,而不是多次输入它。
最后,我将为每个连接使用一个using语句,以确保正确处理它们只是一些额外的想法。您的代码甚至无法编译,因为Convert.ToDateTime返回的是DateTime而不是int。将CommandText发送到ToDateTime方法没有意义。您需要首先执行查询并将其强制转换为datetime或datetime2类型的datetime。请根据您的问题创建一个。也不要尽可能多地使用AddWithValue。使用Add方法重载指定参数类型及其大小。使用using语句也可以自动处理您的连接和命令。如果写入Convert.ToInt32 int,则会编译但随机显示。select MAXStartData from[Events]查询会准确返回什么?StartData列的类型是什么?StartData列是DateTime,MAXStartData是插入数据库的最后一个数据。