473,394 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

DataGrid data keeping refference to previous data

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/Window...44c.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.Grid ColumnStyles[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(CourseC rossTable).name");

DBDataSet.Tables["CoursePerson"].Columns.Add("price",typeof(string),"Parent(Course CrossTable).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,"Pers on.address");
txtBalance.DataBindings.Add("Text",DBDataSet,"Pers on.balance");
txtId.DataBindings.Add("Text",DBDataSet,"Person.id entification");
txtLastName.DataBindings.Add("Text",DBDataSet,"Per son.lastName");
txtName.DataBindings.Add("Text",DBDataSet,"Person. name");
txtTimeStamp.DataBindings.Add("Text",DBDataSet,"Pe rson.timeStamp");

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

private void cboOID_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (!DisableSelectedIndexChanged)
AutoSizeTable(grdCourses);
}
Nov 17 '05 #1
2 2481
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
Nov 17 '05 #2
Hi Bart,
You could use the CurrentChanged event from the CurrencyManager for the
Person table, eg:

Jup, that did the trip.

Thanks,
Josef
Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: pei_world | last post by:
I want to implement a key hit with enter to dropdown a combobox that is in the datagrid. in this case I need to override its original behaviours. I found some codes from the web. Does anyone know...
0
by: MrNobody | last post by:
hey guys... I'm trying to make my DataGrid have selection behavior similar to WindowsExplorer, where I can hold CTRL to add rows to a multi-row selection. Thanks to someone else on this...
1
by: Andrew | last post by:
Hey all, I am very new to ASP.Net (and .Net in general), but that isn't stopping the boss from wanting to begin new projects in it. This latest project has me kinda stumped and after a couple...
4
by: tshad | last post by:
I am having trouble with links in my DataGrid. I have Links all over my page set to smaller and they are consistant all over the page in both Mozilla and IE, except for the DataGrid. Here is a...
5
by: Manny Chohan | last post by:
i have the following situatin: In datagrid i click on hyperlink button to navigate to the detail.aspx page which displays detailed information regarding item id passed from datagrid. Can i put...
5
by: tshad | last post by:
Is there a way to carry data that I have already read from the datagrid from page to page? I am looking at my Datagrid that I page through and when the user says get the next page, I have to go...
4
by: Pacific Design Studios | last post by:
I have a DataGrid on Form1 that displays a small amount of information about employees. On Form2 I want to have all the data displaying in text boxes about the employee selected in the datagrid on...
10
by: Aaron Smith | last post by:
If I have a datagrid and the bound data file only have 4 rows in it, the grid will show the 4 rows. However, there is blank space below that until it reaches the bottom of the grid. Is there a way...
0
by: cms3023 | last post by:
I have a DataGrid which displays data with the aid of a procedure. I have tested the procedure inside the database and it is working fine. The table inside the database has data that matches with...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.