[英]add row to a dynamic datagridview
我有一個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的行集合中。
拜托,任何建議
由於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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.