"I am using datagrid to display records from access db. I got the first field as ID which is primary key. As users should not edit it i made that column as read only but i need that column to be editable when users tries to add a new record(row). I am using windows forms (vb.net)"
Now I tried to solve this problem and this is what I've got:
// Step 1 |
DataGridTableStyle tableStyle = new DataGridTableStyle(); |
tableStyle.MappingName = "Products"; |
DataColumnCollection myDataColumns = ds.Tables["Products"].Columns; |
// Step 2 |
DataGridTextBoxColumn dgTbCol; |
foreach (DataColumn dataColumn in myDataColumns) |
{ |
dgTbCol = new DataGridTextBoxColumn(); |
dgTbCol.MappingName = dataColumn.ColumnName; |
dgTbCol.ReadOnly = true; |
tableStyle.GridColumnStyles.Add(dgTbCol); |
} |
dataGrid1.TableStyles.Add(tableStyle); |
// Step 3 |
ds.Tables["Products"].TableNewRow += new DataTableNewRowEventHandler(Form1_TableNewRow); |
ds.Tables["Products"].RowChanged += new DataRowChangeEventHandler(Form1_RowChanged); |
dataGrid1.CurrentCellChanged +=new EventHandler(dataGrid1_CurrentCellChanged); |
private void Form1_TableNewRow(Object sender, DataTableNewRowEventArgs e) |
{ |
currentRow = (sender as DataTable).Rows.Count; |
GridColumnStylesCollection gcsc = dataGrid1.TableStyles["Products"].GridColumnStyles; |
DataRowCollection drc; |
foreach (DataGridTextBoxColumn dgTbCol in gcsc) |
{ |
if (dataGrid1.CurrentCell.RowNumber == currentRow) |
{ |
Console.WriteLine(dataGrid1.CurrentCell.RowNumber) ; |
dgTbCol.ReadOnly = false; |
} |
} |
} |
private void Form1_RowChanged(Object sender, DataRowChangeEventArgs e) |
{ |
GridColumnStylesCollection gcsc = dataGrid1.TableStyles["Products"].GridColumnStyles; |
foreach (DataGridTextBoxColumn dgTbCol in gcsc) |
{ |
dgTbCol.ReadOnly = true; |
} |
} |
private void dataGrid1_CurrentCellChanged(Object sender, EventArgs e) |
{ |
GridColumnStylesCollection gcsc = dataGrid1.TableStyles["Products"].GridColumnStyles; |
foreach (DataGridTextBoxColumn dgTbCol in gcsc) |
{ |
// currentRow should be a global variable |
if (dataGrid1.CurrentCell.RowNumber != currentRow) |
{ |
Console.WriteLine(dataGrid1.CurrentCell.RowNumber) ; |
dgTbCol.ReadOnly = true; |
} |
} |
} |
Now I'm sure this isn't the best way to do and I have One REMARK: i've made all columns readonly and then is added a new row all are editable in new row. U can make minor changes to accomodate it to ur requirements.
U should pay attention to events TableNewRow, RowChanged, and CurrentCellChanged, if u have questions ask.