473,851 Members | 2,270 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 2509
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
4345
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
1438
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
3303
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
3503
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
1377
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
2799
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
2214
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
8149
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
1776
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
9895
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
9744
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,...
1
10725
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9503
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7900
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
7072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5931
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4547
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
4142
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.