0
votes

i have a windows form where i am trying to add the path of a file usnig folderbrowserDialog

i have this code on at form load

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;
    }

this is the code when i click a button to search for folders and add the path to the above gridview which already has the above row

private void AddPubPath_Button_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            dataGridView2.Rows.Add(false, folderBrowserDialog1.SelectedPath, DateTime.Now);
        }

but i get the following error..

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

please, any suggestions

1

1 Answers

2
votes

Since your DataGridView is bound to a DataTable, you'll need to update your DGV through your DT. That's what the error is telling you.

Update your button click code to the following:

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);
    }
}

This code gets the DataTable your DGV is bound to, creates an empty new row for the table, populates this new row with data and then finally adds the row to the DataTable.

I've also added code that makes sure the user actually selected a folder with your FolderBrowserDialog before attempting to add the row.

Edit in response to your question about making only the Check column editable

// Make all the columns you don't want editable read only.
table.Columns["Path"].ReadOnly = true;
table.Columns["Date"].ReadOnly = true;