我在从文本文件加载并将该信息放入数据网格视图时遇到困难,该数据网格视图是使用绑定源进行数据绑定的。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 回答
青春有我
TA贡献1784条经验 获得超8个赞
代替:
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();
开心每一天1111
TA贡献1836条经验 获得超13个赞
您可以尝试添加下面的代码
BindingSource SBind = new BindingSource();
SBind.DataSource = dataTable;
MoviesDataGridView.Columns.Clear();
MoviesDataGridView.DataSource = SBind;
参考自: How to bind datatable to datagridview in c#
- 2 回答
- 0 关注
- 106 浏览
添加回答
举报
0/150
提交
取消