473,386 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,386 software developers and data experts.

Datatable position

Hi

I have following problem.
I have a datatable filled with some data. Each row holds its ID (column
named "Row_ID")

DataTable dtTable;

I have a datagrid to which I assign this datatable. I also apply some
styling to this datagrid so I only see some columns from this table
(let's say "Name", "SureName" ... "Row_ID" stays hidden)

//simplified
Datagrig dgGrid;
dgGrid.DataSource = dtTable;

Now datagrid is showing my data. Now, I add simple Event where I want
to display a ID of currently clicked row (no matter it does for each
cell).

private void dgGrid_CurrentCellChanged(object sender, System.EventArgs
e) {

MessageBox.Show(dtTable.Rows[this.BindingContext[dtTable].Position]["Row_ID"]);
}

Everything seems to work OK UNTIL I sort the datagrid (by clicking on
one of the column headers). From this moment ON everything is messed
up, and bindings context position is always a row number.

Can anyone help me with:
How do you get a rowNumber in datasource assigned to some datagrid
after there was some ordering done after this source was assigned to
it?

Thanks a lot in advance!

Tomi

Nov 17 '05 #1
3 6027
I ran into the same issue a few months ago.

Apparently the grid resorts the default view of the table when you click a
column. This causes things to get out of sync. The good news is that you
can stay in sync a couple of ways:

1. Set the Table.DefaultView.Sort property to match the column that is being
clicked.
or
(not sure this will work for you)
2. Set the Table.DefaultView.Sort property to the Row_ID and then use the
Table.DefaultView.Find method to get the row you want.
or
3. You might try creating a separate DataView and locating the row you
want???? You wouldn't have to worry about resetting the Sort propery each
time a column header is clicked.

For online help checkout: DataView class (DefaultView is derived from
DataView).

:-)
"tomi" <to**********@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Hi

I have following problem.
I have a datatable filled with some data. Each row holds its ID (column
named "Row_ID")

DataTable dtTable;

I have a datagrid to which I assign this datatable. I also apply some
styling to this datagrid so I only see some columns from this table
(let's say "Name", "SureName" ... "Row_ID" stays hidden)

//simplified
Datagrig dgGrid;
dgGrid.DataSource = dtTable;

Now datagrid is showing my data. Now, I add simple Event where I want
to display a ID of currently clicked row (no matter it does for each
cell).

private void dgGrid_CurrentCellChanged(object sender, System.EventArgs
e) {

MessageBox.Show(dtTable.Rows[this.BindingContext[dtTable].Position]["Row_ID"]);
}

Everything seems to work OK UNTIL I sort the datagrid (by clicking on
one of the column headers). From this moment ON everything is messed
up, and bindings context position is always a row number.

Can anyone help me with:
How do you get a rowNumber in datasource assigned to some datagrid
after there was some ordering done after this source was assigned to
it?

Thanks a lot in advance!

Tomi

Nov 17 '05 #2
Thanks a lot charlie!
I went for point 3, as I could not apply find function because I don't
see the "key .. or ID" field in mine datagrid. Here is my solution if
someone runs into similar troubles.

/* Class level
Datagrid has set AllowSort = false !!!
Main table holding base, unsorted data. This table is bind to the
grid and
to other controls. I use View to sort the records */
private DataTable dtMain;
/* Side table where i sort my data based on selected sorting in grid */
private DataTable dtSide;
/* In this field i hold a list of "true/false" values per each column
on grid
where "true" means "sort ASC" and false "DESC". */
private bool[] fdAscDesc;
/* Last clicked column header */
private string lastClicked;

//FormLoad level
private void Form1_Load(object sender, System.EventArgs e) {
OleDbDataAdapter adapt = new OleDbDataAdapter();
string command = "SELECT * FROM Main";
adapt.SelectCommand = new OleDbCommand(command, conn);
dtMain = new DataTable();
adapt.Fill(dtMain);

/* Table "Main" Consists of 3 columns ["Row_ID","Name","SureName"]
and
there exists a tablestyle where I define that on the grid I only
see
column "Name" and "SureName" (this is the main problem []not
seing ID).
dgClicky is my datagrid */

dtMain.DefaultView.Sort = "Name";
dgClicky.DataSource = dtMain.DefaultView; //or just dtMain

/* Now we'll copy the data from main table to Side table sorted by
the
column "Name" as it is sorted by default. By doing this we'll be
able to
address a rownumber in side table by rownumber of the grid */

dtSide = dtMain.Clone();
foreach (DataRow dr in dtMain.Select("","Name"))
dtSide.ImportRow(dr);

//Set than all columns are now sorted as "ASC" (Ascending)
fdAscDesc = new bool[] { true , true };
lastClicked = "Name";
}

/* In this method we'll handle the sorting of the grid as we've
disabled it. We've done this due to problems it has (it does not handle
all the clicks when user clicks very fast, or double clicks it ..
a.s.o. .. this is safe version of sorting of the grid) */

private void HandleHeaderClick() {
Point pt = this.dgClicky.PointToClient(Cursor.Position);
DataGrid.HitTestInfo hti = this.dgClicky.HitTest(pt);

/* Test if and which column header was last clicked */
if(hti.Row == -1 && hti.Column >= 0){
/* See if we're going to sort ASC(true) or DESC(false) */
if (dtMain.Columns[hti.Column].ColumnName == lastClicked)
fdAscDesc[hti.Column] = !(fdAscDesc[hti.Column] && true);
else fdAscDesc[hti.Column] = true;

dtSide.Clear();
string howSort = fdAscDesc[hti.Column] ? " ASC" : " DESC";
/* Clear side table and copy new sorted values */
foreach (DataRow dr in dtMain.Select("",
dtMain.Columns[hti.Column].ColumnName + howSort))
dtSide.ImportRow(dr);
/* Set last clicked column so we'll know how we're going to
sort next
time */
lastClicked = dtMain.Columns[hti.Column].ColumnName;

//Resort the grid by the clicked column and ASC or DESC
dtMain.DefaultView.Sort = dtMain.Columns[hti.Column].ColumnName +
howSort;
}
}

/* Handle onclick event of the grid */
private void dgClicky_Click(object sender, System.EventArgs e) {

HandleHeaderClick();
}
I hope this will help to someone, it costed me 2 days of my life ....
I'm probably just lame.

Tx.

T.

Nov 17 '05 #3
OK ;)

And now something completely different and way easier than previous ;)

DataRowView dw = (DataRowView)this.BindingContext[dtTable].Current;
MessageBox.Show(dw["Row_ID"].ToString());

tx to Bart Mermuys for this solution

Tomi

Nov 17 '05 #4

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

Similar topics

0
by: Dave Elliott | last post by:
After inserting a new data row to a DataTable that is bound to a datagrid, I am unable to change data in a row that is after the newly added row without getting bizarre results. I have added the...
0
by: tomi | last post by:
Hi I have following problem. I have a datatable filled with some data. Each row holds its ID (column named "Row_ID") DataTable dtTable; I have a datagrid to which I assign this datatable....
2
by: ven | last post by:
Hello i have a dynamic datatable in my page. I wanna to write data to textboxes and after click on button "ADD data" i want to refresh datagrid on page... Here is my code : ' Insert page code...
7
by: Zorpiedoman | last post by:
I'm confused. I have a listbox. The DataSource is a DataTable based on a SQL Select Statement that includes a where clause. For example, "Select ID, FirstName, LastName From Employees where...
1
by: JohnR | last post by:
I'm using oledb to an Access datatable. I load the table into a dataset. I create databindings to link the fields on my form to the corresponding fields in the datatable. The tables...
2
by: DubSport | last post by:
I have created a datatable in a function, and it is populated with data. I want to call a new function from an ASP button, and write out some of the values in the datatable, using: string...
0
by: Ryan Liu | last post by:
I have a program works fine in .NET 1.1 and just recompiled in .NET 2.0 without any code change. Compiles OK, but there is an exeception when execute it. Then I remove PK, it works all fine...
6
by: fniles | last post by:
I am using VB.NET 2005 and Access database. My program uses a timer that kicks in every 1 min to read from a database and copy the dataset table to a datatable. This database is in a class called...
1
by: =?Utf-8?B?UGF1bA==?= | last post by:
I have an existing datatable with 3 rows. I want to programatically add another row but I want to insert that new row in the first position/row of the datatable. I know who to add the new row...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
0
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...
0
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,...
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...

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.