Solved

Does a DataGrid have a value property?

Posted on 2007-03-20
15
204 Views
Last Modified: 2013-12-17
Hi all, coding C# in VS.NET 2003

I'm databinding a recordset to a datagrid and when the user selects a row in the grid I need to return the primary key value.  What I've been doing is just using the CurrentRowIndex and getting that record from the DataSet.  It's been working fine but then I tried sorting the records and it no longer works because now the row indexes in the grid do not reflect the indexes in the dataset.

I'm wondering if DataGrids have a value property similar to a combo box OR if there is a better way of accomplishing my goal.
0
Comment
Question by:alexatsearidge
  • 8
  • 7
15 Comments
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
There is no Value property.  Best way is to add the primary key as a column in the datagrid.  Or use a DataView to give you a view back into the source datatable.  Then don't sort the dataview.
0
 

Author Comment

by:alexatsearidge
Comment Utility
The user needs to be able to sort the DataGrid and the primary key must be hidden.  
I format my dataview to hide the first column and then bind it to the grid.
0
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
You could add the primary key as a hidden field (<asp:HiddenField value='<%# Eval("keyField")%>'/>) in one of the columns.  You need to have it in the DataGrid in some fashion to know which record you are dealing with.
0
 

Author Comment

by:alexatsearidge
Comment Utility
I don't mind if it is in the grid, as long as it is not visible.
Could you provide a code sample?  Also this is a stand alone dialog based application.  I'm not using ASP.
0
 
LVL 25

Accepted Solution

by:
dstanley9 earned 500 total points
Comment Utility
Sorry I asumed you were in web forms.  The DataGrid will bind to the table's DefaultView be default, so it should pick up the sorting from there.

try using

DataRowView row = dataTable.DefaultView[dataGrid.CurrentRowIndex];

Note that it won't be type-safe (and you can't cast to a type-safe row) but you can get the primary key from there.
0
 

Author Comment

by:alexatsearidge
Comment Utility
Which brings us back to the original problem.  The grid and the view are not consistent in the sorting.  Do I need to handle when the Grid is sorted in order to sort the DataView?
0
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
I guess I didn't say that right.  The DataGrid should use the DefaultView of the data table by default.  So when you sort the DataGrid, the DefaultView should be sorted as well and should match the DataGrid.  So you can get the selected row (even if the grid has been sorted) by using:

DataRowView row = dataTable.DefaultView[dataGrid.CurrentRowIndex];
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:alexatsearidge
Comment Utility
I hear what you're saying, I'm just not getting those results.  I don't think my view is sorting with the datagrid.  Here is my code:

// Bind the view to the dataset
myDataView = myDataSet.Tables[0].DefaultView;
myDataGrid.DataSource = myDataView;

// Get the value of the first cell in the current row
DataRowView row = dvCaseHistory[dataGrid.CurrentRowIndex];
scheduleID = Convert.ToInt32(row[0]);

See any reason why sorting the grid would not sort my view?  My view is in a separate class if that makes a difference.
0
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
Where are you getting dvCaseHistory?  Is it the same as myDataSet.Tables[0].DefaultView?  When I ran it the view index matched the selected row in the datagrid - I am using VS 2005, but I remember the behavior to be the same in VS 2003 as well.
0
 

Author Comment

by:alexatsearidge
Comment Utility
Yes sorry it is the same as myDataView.  Did you try sorting you datagrid and then seeing if the index returned the proper value?

Try putting a few rows ("A", "B", "C") at positions 1, 2 and 3 respectively.  
Then sort descending so that the order displayed is C, B, A.  Then select C and see if Row 1 in your dataview is returning C.
0
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
Yes.  I created a datagrid that alowed sorting (in my case I was sorting on the 5th column).  I then added a button that showed the 5th column in the row of the dataview at the selected index.

Here's my codebehind:


        private DataTable _data;
        public Form3()
        {
            InitializeComponent();

            _data = {code to get datatable}

            BindData();
        }

        private void BindData()
        {

            dataGrid1.DataSource = _data;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataRowView row = _data.DefaultView[dataGrid1.CurrentRowIndex];
            MessageBox.Show(_data.DefaultView.Sort);  // show the current sort order
            MessageBox.Show(row[4].ToString()); // show the value of the 5th column
        }

This showed me the correct sort order (based on the column header I clicked) and the value of the 5th column regardless of the sort order (I could sort on different columns, asc or desc, and it still worked).
I'm wondering if your dvCaseHistory is pointing to the same DataView as your DataSource.  
0
 

Author Comment

by:alexatsearidge
Comment Utility
Tried your code, I'm still getting the unsorted tables values.

Note:
Wehn I inserted your code with the messages boxes and ran it, they do not appear.  I traced through and for some reason it seems to jump past the code.  The code appears to run because one of my variables is populated.

I wonder if this has anything to do with the problem.
0
 
LVL 25

Expert Comment

by:dstanley9
Comment Utility
It probably didn't wire up the click event.  double-click on the button to create a click event, then paste the code in.  Are you certain that dvCaseHistory is pointing to the default view of the data table?  Can you post the code snippets that:

* assigns dvCaseHistory
* binds the datagrid
* gets the sleected index of the grid and tryies to get the matching row
0
 

Author Comment

by:alexatsearidge
Comment Utility
Got it, its working.  

Problem was that I was creating my view from a dataset, binding the view to the Grid, then when I was trying to get the cell value I was looking in the dataSet, not the view.  Using the view works perfect.
0
 

Author Comment

by:alexatsearidge
Comment Utility
Thanks so much for your patience.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now