总的来说,我是编程的初学者。我的应用程序有一个按钮,上面列出了DGV上选定文件的名称。我使用DGV任务在windows窗体设计器上添加了一行文件名。守则如下:
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
ofd.Multiselect = true;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] dateinamen = ofd.SafeFileNames;
for (int i = 0; i < ofd.FileNames.Count() - 1; i++)
{
dataGridView1.Rows.Add(dateinamen[i]);
}
}
} 在创建此按钮后,我创建了一个类作为该DGV的数据源(在windows窗体设计-> DGV任务-> source -> Object -> class创建)然后,我尝试使用上面提到的按钮打开文件以列出它们的名称。我得到以下消息:“当控件绑定数据时,不能以编程方式将行添加到DataGridView的行集合中”。
我能理解为什么,我想解决这个问题。最好的选择是,我想,把ofd代码放到Datasource类中,但是我不知道怎么做。我甚至不确定这样做是否正确。如果没有,如果我能找到正确的方法来解决这个问题,那就太好了。
提前感谢!
发布于 2022-04-11 10:20:21
BindingList<Datei> dateienList = new BindingList<Datei>();
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
ofd.Multiselect = true;
try
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (String path in ofd.FileNames)
{
Datei datei = new Datei();
datei.filePath = path;
datei.Dateiname = Path.GetFileName(path);
dateienList.Add(datei);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Fehler! Die Datei kann nicht gelesen werden: " + ex.Message);
}
}
public class Datei //class as Datasource
{ //
[DisplayName("Dateiname")]
public string Dateiname { get; set; }
public string filePath { get; set; }
}
}https://stackoverflow.com/questions/71415319
复制相似问题