我在从文本文件加载并将该信息放入数据网格视图时遇到困难,该数据网格视图是使用绑定源进行数据绑定的。
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’类型。”
青春有我
开心每一天1111
相关分类