473,573 Members | 2,944 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 SelectionChange Committed, 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(Ole DbConnection conn, DataSet dataSet, string
tableName)
{
string selectCommand;
OleDbDataAdapte r dbAdapter;

dbAdapter = new OleDbDataAdapte r();
selectCommand = "SELECT * FROM " + tableName;
dbAdapter.Selec tCommand = new OleDbCommand(se lectCommand);
dbAdapter.Selec tCommand.Connec tion = conn;
dbAdapter.Fill( dataSet,tableNa me);
}

//This peace of code autosizes a DataGrid columns to fit the size of the
current
//data.
public void AutoSizeTable(D ataGrid grid)
{
DataGridTableSt yle tableStyle;
tableStyle = grid.TableStyle s[0];
if ((grid.DataSour ce != null) && (tableStyle != null))
{
int numCols = tableStyle.Grid ColumnStyles.Co unt;
for(int i = 0; i < numCols; ++i)
AutoSizeCol(gri d,i);
}
}

public void AutoSizeCol(Dat aGrid grid, int col)
{
float width;
CurrencyManager childCurrencyMa nager;
CurrencyManager parentCurrencyM anager;
DataGridTableSt yle tableStyle;

tableStyle = grid.TableStyle s[0];
childCurrencyMa nager =
(CurrencyManage r)grid.BindingC ontext[DBDataSet,grid. DataMember];
parentCurrencyM anager =
(CurrencyManage r)grid.BindingC ontext[DBDataSet,"Pers on"];
int numRows = childCurrencyMa nager.Count;

Graphics g = Graphics.FromHw nd(grid.Handle) ;
StringFormat sf = new StringFormat(St ringFormat.Gene ricTypographic) ;
SizeF size;

//First gets the width of the header. Sometimes the header is longer as the
//data.
size = g.MeasureString (
tableStyle.Grid ColumnStyles[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.Grid ColumnStyles[col].Width = (int) width + 16;
}

private void InitGridStyles( DataGrid grid)
{
CurrencyManager currencyManager ;
DataGridTableSt yle tableStyle;
currencyManager =
(CurrencyManage r) BindingContext[DBDataSet, "Person.PersonC rossTable"];
tableStyle = new DataGridTableSt yle(currencyMan ager);
// Add the table style to the collection of a DataGrid.
grid.TableStyle s.Clear();
//Removes the Person_OID column
tableStyle.Grid ColumnStyles.Re move(tableStyle .GridColumnStyl es[0]);
grid.TableStyle s.Add(tableStyl e);
}
private void frmDataBinding_ Load(object sender, System.EventArg s e)
{
DataColumn parentCol;
DataColumn childCol;
DataColumn[] primaryKeys;
DataRelation relationShip;

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

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

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

//We fill the record set with the Person records
FillDataSet(DBC onnection,DBDat aSet,"Person");
primaryKeys = (DataColumn[])Array.CreateIn stance(typeof(D ataColumn),1);
primaryKeys[0] = DBDataSet.Table s["Person"].Columns["OID"];
DBDataSet.Table s["Person"].PrimaryKey = primaryKeys;

//We fill the DataSet with the Courses and the cross refference table
//CoursePerson
FillDataSet(DBC onnection,DBDat aSet,"Course");
FillDataSet(DBC onnection,DBDat aSet,"CoursePer son");

//Then we set the relationship between Person and CoursePerson
parentCol = DBDataSet.Table s["Person"].Columns["OID"];
childCol = DBDataSet.Table s["CoursePers on"].Columns["Person_OID "];
relationShip = new
DataRelation("P ersonCrossTable ",parentCol,chi ldCol,true);
relationShip = new DataRelation("P ersonCrossTable ",parentCol,chi ldCol);
DBDataSet.Relat ions.Add(relati onShip);

//Finally the relation between CoursePerson and Course is being set
parentCol = DBDataSet.Table s["Course"].Columns["OID"];
childCol = DBDataSet.Table s["CoursePers on"].Columns["Course_OID "];
relationShip = new
DataRelation("C ourseCrossTable ",parentCol,chi ldCol,true);
DBDataSet.Relat ions.Add(relati onShip);

//Some calculated rows are added

DBDataSet.Table s["CoursePers on"].Columns.Add("n ame",typeof(str ing),"Parent(Co urseCrossTable) .name");

DBDataSet.Table s["CoursePers on"].Columns.Add("p rice",typeof(st ring),"Parent(C ourseCrossTable ).price");
}
catch (InvalidOperati onException exception)
{
MessageBox.Show ("Connection is already open: " + exception.Messa ge);
}
catch (OleDbException exception)
{
MessageBox.Show ("Ole Exception: " + exception.Messa ge);
}
catch (Exception exception)
{
MessageBox.Show ("Unexpected exception occured: " + exception.Messa ge);
}

//First we bind the parent records
cboOID.DataSour ce = DBDataSet;
cboOID.DisplayM ember = "Person.OID ";
cboOID.ValueMem ber = "Person.OID ";

txtAddress.Data Bindings.Add("T ext",DBDataSet, "Person.address ");
txtBalance.Data Bindings.Add("T ext",DBDataSet, "Person.balance ");
txtId.DataBindi ngs.Add("Text", DBDataSet,"Pers on.identificati on");
txtLastName.Dat aBindings.Add(" Text",DBDataSet ,"Person.lastNa me");
txtName.DataBin dings.Add("Text ",DBDataSet,"Pe rson.name");
txtTimeStamp.Da taBindings.Add( "Text",DBDataSe t,"Person.timeS tamp");

grdCourses.SetD ataBinding(DBDa taSet,"Person.P ersonCrossTable ");
InitGridStyles( grdCourses);
AutoSizeTable(g rdCourses);
DisableSelected IndexChanged = false;
}

private void cboOID_Selected IndexChanged(ob ject sender, System.EventArg s e)
{
if (!DisableSelect edIndexChanged)
AutoSizeTable(g rdCourses);
}
Nov 17 '05 #1
2 2491
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(On CurrentChanged) ;

And then add this method:

private void OnCurrentChange d(object sender, EventArgs e)
{
AutoSizeTable(g rdCourses);
}
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
4325
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 how to use this code? please help! http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20862953.html
0
1424
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 newsgroup, I found out how to detect if CTRL is pressed while in my MouseUp event, which is when it's supposed add that row to the selection. (Otherwise, if...
1
3267
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 days of struggling, I figure asking you all (the experts) will keep me from going down some dark and dangerous road. The project I have is a fairly...
4
3483
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 snippet from my .css file: *************************** body { margin:0; padding:0;
5
1370
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 arrows(up/down) on detail.aspx so that i can retrieve next/previous corresponding item in datagrid? Is this possible? Can someone recomend any article...
5
2767
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 to the database to get the next page. Is there a way to use the dataset to allow us to read back and forth in it instead of going back to the...
4
2198
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 form 1. Is there a Id in the datagrid I can use to find out which user was selected or which record was highlighted when double clicked. Something...
10
8105
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 to have a fixed number of rows regardless of what data is in the bound table? Thanks, Aaron -- --- Aaron Smith
0
1765
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 the parameter. I have another procedure which adds another row to the table, which is working fine inside the programming, and in the database. ...
0
7771
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8009
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8198
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7771
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6406
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3730
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2194
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1296
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.