我有一个Windows窗体,我试图添加文件路径usnig folderbrowserDialog
我在表单加载时有这段代码
public FileMgmt()
{
InitializeComponent();
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Check", typeof(bool));
table.Columns.Add("Path", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(false, "", DateTime.Now);
dataGridView2.DataSource = table;
}
当我点击按钮搜索文件夹并将路径添加到上面已经有上面一行的gridview时,这是代码
private void AddPubPath_Button_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
dataGridView2.Rows.Add(false, folderBrowserDialog1.SelectedPath, DateTime.Now);
}
但是我收到以下错误..
当控件受数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。
请,任何建议
答案 0 :(得分:2)
由于您的DataGridView绑定到DataTable,您需要通过DT更新您的DGV。这就是错误告诉你的。
将按钮点击代码更新为以下内容:
private void button1_Click(object sender, EventArgs e) {
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
var table = (DataTable)dataGridView2.DataSource;
var newRow = table.NewRow();
newRow["Check"] = false;
newRow["Path"] = folderBrowserDialog1.SelectedPath;
newRow["Date"] = DateTime.Now;
table.Rows.Add(newRow);
}
}
此代码获取您的DGV绑定的DataTable,为表创建一个空的新行,使用数据填充此新行,然后最后将该行添加到DataTable。
我还添加了代码,确保用户在尝试添加行之前实际选择了FolderBrowserDialog的文件夹。
编辑以回答有关仅使“检查”列可编辑的问题
// Make all the columns you don't want editable read only.
table.Columns["Path"].ReadOnly = true;
table.Columns["Date"].ReadOnly = true;