473,715 Members | 6,082 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 2503
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
4328
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
1427
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 the CTRL key is not pressed I clear any current selection to start over- just like Explorer) ...
1
3288
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 simple one, in theory anyway. The gist is to create a page where the user enters an IDNumber,...
4
3493
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
1371
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 which explains how to achieve this in C#? Thanks Manny
5
2789
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 database to get it? Thanks,
4
2209
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 like: John Thomas Employee Id 2637 was selected on Form1 and the recordset on Form2 would use...
10
8126
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
1770
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. However, I still cannot figure out what am I doing wrong with the DataGrid configurations OR...
0
8823
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9198
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4477
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3175
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
2
2541
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2119
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.