【发布时间】:2018-07-26 10:43:14
【问题描述】:
我是编程新手(大学一年级学习),我正在开发一个小型应用程序。
我有一个窗口,用户可以在其中将数据从 SQL 检索到 DataGrid 和一个 Button 用于将一些数据从 DataGrid 数据导出到文本文件。
这是我用来从 SQL 获取数据的代码:
SqlConnection con = new SqlConnection("Server = localhost;Database = autoser; Integrated Security = true");
SqlCommand cmd = new SqlCommand("selectproduct", con); // Using a Store Procedure.
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("dtList");
cmd.Parameters.AddWithValue("@Code", txtbarcode.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
data.ItemsSource = dt.DefaultView;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
if (count == 0)
{
MessageBox.Show("This product doesn't excist");
SystemSounds.Hand.Play();
}
else if (count == 1)
{
lblinfo.Visibility = Visibility.Visible;
SystemSounds.Asterisk.Play();
}
而这个是我用来写文本文件的代码:
{
using (StreamWriter writer = new StreamWriter("D:\\test.txt", true))
{
writer.WriteLine("Welcome");
writer.WriteLine("E N T E R N E T");
}
using (StreamWriter writer = new StreamWriter("D:\\test.txt", true))
{
writer.WriteLine(data.Items);
}
using (StreamWriter writer = new StreamWriter("D:\\test.txt", true))
{
writer.WriteLine(data.Items);
}
// Append line to the file.
using (StreamWriter writer = new StreamWriter("D:\\test.txt", true))
{
writer.WriteLine("---------------------------------------");
writer.WriteLine(" Thank You! ");
writer.WriteLine(" " + DateTime.Now + " ");
}
}
当我打开文本文件时,我得到了这个数据
Welcome
E N T E R N E T
System.Windows.Controls.ItemCollection - Why isn't show the data grid
data
---------------------------------------
Thank You
7/26/2018 12:38:37 PM
我的问题是:我的错误在哪里导致 DataGrid 中的数据没有以正确的方式显示?
提前致谢
【问题讨论】:
-
您当前正在编写
data.Items对象的默认ToString实现,如果是System.Windows.Controls.ItemCollection,如果您想打印每个项目,那么您需要遍历每个项目,然后打印所需值 -
为了在文件中存储早午餐数据,我建议将它们序列化为 Xml 或 Json。这样您的数据将被正确转义并且保存检索信息将很容易。
标签: c# sql wpf text-files