如何读取文本文件并将数据添加到具有绑定源的数据网格视图中

时间:2019-04-01 10:56:23

标签: c# winforms

我难以从文本文件加载,并且无法将该信息放入使用绑定源进行数据绑定的数据网格视图中。

private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
{
    Stream myStream = null;

    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "Text File|*.txt";
    var result = openFileDialog.ShowDialog();
    DataTable dataTable = (DataTable)MoviesDataGridView.DataSource;
    DataRow dtRow = (DataRow)MoviesDataGridView.DataSource;

    if (result != DialogResult.OK)
        return;
    try
    {
        using (myStream = openFileDialog.OpenFile())
        {
            string newline;
            StreamReader file = new StreamReader(myStream);
            while ((newline = file.ReadLine()) != null)
            {
                string[] lines = newline.Split('\t');
                for (int i = 0; i < lines.Length; i++)
                {
                    dtRow[i] = lines[i];
                }
                dataTable.Rows.Add(dtRow);
            }

            file.Close();
            MoviesDataGridView.DataSource = dataTable;
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk.  Original error: " + ex.Message);
    }
}

想打开它,然后加载到dataGridView中,但是我收到此异常错误:

  

System.InvalidCastException:'无法将类型为'System.Windows.Forms.BindingSource'的对象转换为类型为'System.Data.DataTable'。”

2 个答案:

答案 0 :(得分:0)

您可以尝试在下面添加代码

BindingSource SBind = new BindingSource();
SBind.DataSource = dataTable;
MoviesDataGridView.Columns.Clear();
MoviesDataGridView.DataSource = SBind;

引用自: how to bind datatable to datagridview in c#

答案 1 :(得分:0)

替换:

DataTable dataTable = (DataTable)MoviesDataGridView.DataSource;
DataRow dtRow = (DataRow)MoviesDataGridView.DataSource;

使用

DataTable dataTable = new DataTable();

像这样在表中添加列:

DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
table.Columns.Add(column);

并在while循环中使用以下命令创建新行:

DataRow dtRow = dataTable.NewRow();