【问题标题】:wpf datagrid from textfile add row vb来自文本文件的 wpf datagrid 添加行 vb
【发布时间】:2015-11-27 09:08:06
【问题描述】:

您好!我对 WPF 很陌生。我猜我有一个简单的需求。我需要在数据网格中显示每一行文本文件。文件中的行数以前不知道。

我正在使用 streamreader 从文本文件中读取行。

当我尝试将内容添加到新行时,正在添加新行但没有内容。

grid1.items.add(t) '其中 t 是从文本文件中读取的行

我认为 t 是项目,我确实知道如何添加项目并为其添加内容。非常感谢您的帮助。

提前非常感谢。

  • 斯里

【问题讨论】:

    标签: wpf vb.net datagrid row


    【解决方案1】:
            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;
    

    试试这个

    【讨论】:

    • 感谢您的及时回复。我正在研究 WPF,但这种方式无法解决。我写如下 Sub test() Dim t As String Dim reader As StreamReader = New StreamReader("D:\1TXC15_TRACE.txt") While reader.Peek -1 t = reader.ReadLine() Grid1.Items.Add (New Binding("Hi" & t.ToString())) End While reader.Close() End Sub
    【解决方案2】:

    添加列并设置正确的绑定是必须的。

    代码中的一切:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-21
      • 2015-04-06
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多