【发布时间】:2015-11-27 09:08:06
【问题描述】:
您好!我对 WPF 很陌生。我猜我有一个简单的需求。我需要在数据网格中显示每一行文本文件。文件中的行数以前不知道。
我正在使用 streamreader 从文本文件中读取行。
当我尝试将内容添加到新行时,正在添加新行但没有内容。
grid1.items.add(t) '其中 t 是从文本文件中读取的行
我认为 t 是项目,我确实知道如何添加项目并为其添加内容。非常感谢您的帮助。
提前非常感谢。
- 斯里
【问题讨论】:
您好!我对 WPF 很陌生。我猜我有一个简单的需求。我需要在数据网格中显示每一行文本文件。文件中的行数以前不知道。
我正在使用 streamreader 从文本文件中读取行。
当我尝试将内容添加到新行时,正在添加新行但没有内容。
grid1.items.add(t) '其中 t 是从文本文件中读取的行
我认为 t 是项目,我确实知道如何添加项目并为其添加内容。非常感谢您的帮助。
提前非常感谢。
【问题讨论】:
System.IO.StreamReader file = new System.IO.StreamReader("filename.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
试试这个
【讨论】:
添加列并设置正确的绑定是必须的。
代码中的一切:
string[] lines = {"line1", "line2" };
DataGridTextColumn col1 = new DataGridTextColumn();
Dgrd.Columns.Add(col1);
col1.Binding = new Binding(".");
Dgrd.Items.Add(lines[0]);
在 XAML 中添加列:
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding .}"/>
</DataGrid.Columns>
没有直接Items.Add:
string[] lines = { "line1", "line2" };
Dgrd.ItemsSource = lines.ToList();
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding .}"/>
</DataGrid.Columns>
【讨论】: