Possible Duplicate:
C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?
I have a sql datatable, and I don't want the users to delete or modify anything, they can only add new rows if they want.
My solution was to use datagridview to show the existing data, but I'm stuck, because I cannot deny editing or deleting without denying adding a new row, so this is not a good way. Otherwise using update method will override all the data the user has changed (later on maybe I can give overriding permissions for that).
I could make a read-only dgw to show the existing data, and allow the user to enter the new data one by one with textboxes, but that's a bigger work and maybe unnecessary.
Is there a simple way to allow adding new row without letting editing the existing data? Maybe manipulating the datatable?
Thank you.
The simpler way i could think of is, while populating the grid, ill see how many existing rows i am adding from DB. Ill keep a count on it. Then when user clicks save, ill update the DB from rows after this count. Once update the DB, ill update the count to new rows count. The same holds good even if you dont want to allow the user to edit, you can write events where you can check if the editable row is less than tis count, then disallow him to edit.
As an alternative you could provide the user with a new Form in order for them to add a new record like a lot of new forms. I liked the idea of a user being able to add a row to a DataGridView but in the end gave up fighting with it. You just have far easier control in a Form as opposed to a row in a DGV.
In answer to your question - Rather than fight the source, perhaps ask the DataGridView to officiate:
dataGridView1.DataSource = bs;
dataGridView1.ReadOnly = true;
dataGridView1.CurrentCellChanged += delegate
{
DataGridViewRow row = dataGridView1.CurrentRow;
bool readOnly = row == null ||
row.Index != dataGridView1.NewRowIndex;
dataGridView1.ReadOnly = readOnly;
};
(and don't set AllowEdit on the list)
Source: C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?
精彩评论