DataGrid data keeping refference to previous data

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

Guest

Hi,

I'm using a ComboBox, some Textboxes, and a DataGrid to represent a
many-to-many relationship between Person and Course. Each time that I change
the value in the ComboBox (which for now is the OID of Person), the
information of the person matching the selected OID is shown in the Textboxes
(Name, Address, id, etc) and the courses this person is taken are shown in a
DataGrid (course name, price, etc.). This is working well so far, I just used
the code shown in this article:

*Displaying Many-to-Many Relationships
http://www.developerfusion.co.uk/show/4491/

Now I want to make my DataGrid look nicer by auto resizing the Columns
according to its largest entry. So, I used the code mentioned here:

* 5.52 How can I autosize a column in my datagrid?
http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c44c.aspx#q877q

I called the method mentioned in the previous faq (AutoSizeTable) in the
combobox's SelectedIndex Event handler. But it seems that when the
SelectedIndex is changed, the DataGrid still has the previous data. I also
tried with the SelectionChangeCommitted, but I got the same results. How can
I solved this problem?

Thanks in advanced,
Josef

Here is the code I'm using:

private void FillDataSet(OleDbConnection conn, DataSet dataSet, string
tableName)
{
string selectCommand;
OleDbDataAdapter dbAdapter;

dbAdapter = new OleDbDataAdapter();
selectCommand = "SELECT * FROM " + tableName;
dbAdapter.SelectCommand = new OleDbCommand(selectCommand);
dbAdapter.SelectCommand.Connection = conn;
dbAdapter.Fill(dataSet,tableName);
}

//This peace of code autosizes a DataGrid columns to fit the size of the
current
//data.
public void AutoSizeTable(DataGrid grid)
{
DataGridTableStyle tableStyle;
tableStyle = grid.TableStyles[0];
if ((grid.DataSource != null) && (tableStyle != null))
{
int numCols = tableStyle.GridColumnStyles.Count;
for(int i = 0; i < numCols; ++i)
AutoSizeCol(grid,i);
}
}

public void AutoSizeCol(DataGrid grid, int col)
{
float width;
CurrencyManager childCurrencyManager;
CurrencyManager parentCurrencyManager;
DataGridTableStyle tableStyle;

tableStyle = grid.TableStyles[0];
childCurrencyManager =
(CurrencyManager)grid.BindingContext[DBDataSet,grid.DataMember];
parentCurrencyManager =
(CurrencyManager)grid.BindingContext[DBDataSet,"Person"];
int numRows = childCurrencyManager.Count;

Graphics g = Graphics.FromHwnd(grid.Handle);
StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
SizeF size;

//First gets the width of the header. Sometimes the header is longer as the
//data.
size = g.MeasureString(
tableStyle.GridColumnStyles[col].HeaderText,
grid.Font, 500, sf);
width = size.Width;
for(int i = 0; i < numRows; ++ i)
{
size = g.MeasureString(grid[i, col].ToString(), grid.Font, 500, sf);
if(size.Width > width)
width = size.Width;
}
g.Dispose();

tableStyle.GridColumnStyles[col].Width = (int) width + 16;
}

private void InitGridStyles(DataGrid grid)
{
CurrencyManager currencyManager;
DataGridTableStyle tableStyle;
currencyManager =
(CurrencyManager) BindingContext[DBDataSet, "Person.PersonCrossTable"];
tableStyle = new DataGridTableStyle(currencyManager);
// Add the table style to the collection of a DataGrid.
grid.TableStyles.Clear();
//Removes the Person_OID column
tableStyle.GridColumnStyles.Remove(tableStyle.GridColumnStyles[0]);
grid.TableStyles.Add(tableStyle);
}


private void frmDataBinding_Load(object sender, System.EventArgs e)
{
DataColumn parentCol;
DataColumn childCol;
DataColumn[] primaryKeys;
DataRelation relationShip;

//First a connection to a access database is created
DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+
@"Data Source=C:\PersistentLayer\Database\test_many-to-many.mdb");

try
{
//We open the connection
DBConnection.Open();

//The DataSet is created
DBDataSet = new DataSet();

//We fill the record set with the Person records
FillDataSet(DBConnection,DBDataSet,"Person");
primaryKeys = (DataColumn[])Array.CreateInstance(typeof(DataColumn),1);
primaryKeys[0] = DBDataSet.Tables["Person"].Columns["OID"];
DBDataSet.Tables["Person"].PrimaryKey = primaryKeys;

//We fill the DataSet with the Courses and the cross refference table
//CoursePerson
FillDataSet(DBConnection,DBDataSet,"Course");
FillDataSet(DBConnection,DBDataSet,"CoursePerson");

//Then we set the relationship between Person and CoursePerson
parentCol = DBDataSet.Tables["Person"].Columns["OID"];
childCol = DBDataSet.Tables["CoursePerson"].Columns["Person_OID"];
relationShip = new
DataRelation("PersonCrossTable",parentCol,childCol,true);
relationShip = new DataRelation("PersonCrossTable",parentCol,childCol);
DBDataSet.Relations.Add(relationShip);

//Finally the relation between CoursePerson and Course is being set
parentCol = DBDataSet.Tables["Course"].Columns["OID"];
childCol = DBDataSet.Tables["CoursePerson"].Columns["Course_OID"];
relationShip = new
DataRelation("CourseCrossTable",parentCol,childCol,true);
DBDataSet.Relations.Add(relationShip);

//Some calculated rows are added

DBDataSet.Tables["CoursePerson"].Columns.Add("name",typeof(string),"Parent(CourseCrossTable).name");

DBDataSet.Tables["CoursePerson"].Columns.Add("price",typeof(string),"Parent(CourseCrossTable).price");
}
catch (InvalidOperationException exception)
{
MessageBox.Show("Connection is already open: " + exception.Message);
}
catch (OleDbException exception)
{
MessageBox.Show("Ole Exception: " + exception.Message);
}
catch (Exception exception)
{
MessageBox.Show("Unexpected exception occured: " + exception.Message);
}

//First we bind the parent records
cboOID.DataSource = DBDataSet;
cboOID.DisplayMember = "Person.OID";
cboOID.ValueMember = "Person.OID";

txtAddress.DataBindings.Add("Text",DBDataSet,"Person.address");
txtBalance.DataBindings.Add("Text",DBDataSet,"Person.balance");
txtId.DataBindings.Add("Text",DBDataSet,"Person.identification");
txtLastName.DataBindings.Add("Text",DBDataSet,"Person.lastName");
txtName.DataBindings.Add("Text",DBDataSet,"Person.name");
txtTimeStamp.DataBindings.Add("Text",DBDataSet,"Person.timeStamp");

grdCourses.SetDataBinding(DBDataSet,"Person.PersonCrossTable");
InitGridStyles(grdCourses);
AutoSizeTable(grdCourses);
DisableSelectedIndexChanged = false;
}

private void cboOID_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (!DisableSelectedIndexChanged)
AutoSizeTable(grdCourses);
}
 
Hi,

You could use the CurrentChanged event from the CurrencyManager for the
Person table, eg:

Remove the combobox event handler and then put the following line as the
last line in your form_Load method:

BindingContext[DBDataSet, "Person"].CurrentChanged+=new
EventHandler(OnCurrentChanged);

And then add this method:

private void OnCurrentChanged(object sender, EventArgs e)
{
AutoSizeTable(grdCourses);
}


HTH,
Greetings
 
Back
Top