Adding/Inserting rows and columns to DataGrid

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I am using this nice control DataGrid. I do everything in runtime. Bind it to dataTable created in runtime too.

I need to add columns and rows in any order. It works when I add rows OR columns, but when I try to add row then column (or in any other combination), I am getting in dataGrid some additional rows.

Adding columns:
private void AddColumnDataGrid(DataGrid dataGrid, int position)
{
DataTable dataTable=new DataTable();
dataTable=(DataTable)dataGrid.DataSource;

int colNo=dataTable.Columns.Count;

DataGridTableStyle ts=dataGrid.TableStyles[0];
int newCount = ts.GridColumnStyles.Count + 1;
DataGridColumnStyle[] colStyles = new DataGridColumnStyle[newCount];

int ind=1;
if (position==(newCount-1))
ind=0;// for insert to the right

int loc = 0;
for(int i = 0; i < newCount-ind; ++i)
{
if(i == position)
{
string newCol="newCol"+Convert.ToString(colNo+1);
dataTable.Columns.Add(newCol, Type.GetType("System.String"));
for(int index = 0; index<dataTable.Rows.Count;++index)
dataTable.Rows[index][colNo] = "999";

colStyles[loc] = new DataGridTextBoxColumn();
colStyles[loc].MappingName =newCol;
colStyles[loc].HeaderText =newCol;
colStyles[loc].Width=100;

loc++;
}
if (loc<newCount)// don't do if insert to the right at the end
{
colStyles[loc] = ts.GridColumnStyles;
loc++;
}
}
ts.GridColumnStyles.Clear();
ts.GridColumnStyles.AddRange(colStyles);

}

Adding rows:
private void AddRowDataGrid(DataGrid dataGrid,int position)
{
DataTable dataTable=new DataTable();
dataTable=(DataTable)dataGrid.DataSource;
DataRow row=dataTable.NewRow();

for (int i=0;i<dataTable.Columns.Count;++i)
row[dataTable.Columns.ColumnName]="888";

dataTable.Rows.InsertAt(row,position);
dataTable.AcceptChanges();

}
Result:
111 999 111 111
111 999 111 111
111 999 111 111
888 (null) 888 888
111 (null) 111 111
111 (null) 111 111
888 999 888 888

Initially I had 3 rows and 3 columns (values 111). I just added one row (888), then one column(999). But got 7 rows now (3 original, 1 new and 3 ???).
Looks like something's wrong with adding rows.
Need your help.

Thank you.
Victor
 
....or maybe somebody can suggest how to add rows and columns to DataGrid in different way?
 
Back
Top