Inserting row into user sorted, data-bound DataGridView

dotnet framework

    Next

  • 1. DataBinding with DateTimePicker Control doesn't work
    Hello, I have created form with data form wizard in VB .Net 2003. I have bind some text box and combo box and it runs properly, but when I am binding DateTimePicker Control with following property it doesn't work : Value Property :- <dataset name>.<Field Name> Any suggession will be appreciated. Hardik
  • 2. .NET Parent/Child table relation
    Hi, Below is my code for setting up a parent/child relation. It seems to work as far setting up the relation is concerned. For instance, I'm using a DataGrid with navigation and I can move from the parent to the child tables and back etc. However, when I delete a row in the parent table, it does not delete the related child table rows. Furthermore, I also have to "manually" set the child table "relation link field" when adding child rows. This does not seem quite right. I've experimented with using ForeignKeyConstraints only, also with no luck (I could not get the parent/child relation working, so I've assumed that this is not the correct method to use). Thanks. RelUnitsRqts = New DataRelation("Unit_Request", _ mDs.Tables(tbls(tbl.Units)).Columns("UnitID"), _ mDs.Tables(tbls(tbl.Requests)).Columns("UnitID")) mDs.Relations.Add(RelUnitsRqts) 'Add relation. With RelUnitsRqts .ChildKeyConstraint.DeleteRule = Rule.Cascade .ChildKeyConstraint.UpdateRule = Rule.Cascade .ChildKeyConstraint.AcceptRejectRule = AcceptRejectRule.Cascade End With
  • 3. How to display all objects of ArrayList (C#)
    Hi, I`ve got a problem, `cos I need to display all the objcets of ArrayList. Every object is a two dimensional array. Is it possible to display object like below? This is a two dimensional array object. Object: xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx I want to dispaly objects like showed below: xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx and so on... Has anyone got any idea??? Thanks
  • 4. Data Editting
    I'm new to VS. I'm using C# so far. I would like to know the preferred way to set up a data connection and grid that allows for editting. So far I've got data showing in a grid using an odbcDataConnection, an odbcDataAdapter, a DataSet, and a dataGrid. I've noticed that the DataAdapter has a UpdateCommand property with a CommandText subproperty and Parameters subproperty. Am I to set the CommandText and Parameters properties using an UPDATE command with a WHERE clause? If this is the case, what would be the appropriated names of the old value and new value parameters? Is there a simpler way of doing this?

Inserting row into user sorted, data-bound DataGridView

Postby Dan Cooperstock » Thu, 14 Jun 2007 23:39:50 GMT

I'm trying to insert a new row at a specific location of a data-bound 
DataGridView. I understand that you would normally do that by inserting the 
row into the bound DataTable. 

The use case is sort of like an accounting situation with a "split" - I am 
entering donations made by donors, and I want another line in the DGV for a 
2nd donation by the same donor. When they click the "Split" button, a new 
row should appear right below the currently selected row, showing the same 
donor name.

The problem  is, I allow my users to sort the DGV by clicking on column 
headers. When they do that, the order of the rows in the DataGridView no 
longer matches the order of the rows in the DataTable, so I can't figure 
out how to get the correct position to insert the DataTable row at, so that 
when it appears in the DataGridView, it is immediately below the previously 
selected row (which it will be a partial copy of).

I think what is happening is that because the sort is on the DGV column, it 
automatically and immediately resorts after the column is added. Unless the  
current DGV sort is on the donor name column, this moves the new row away 
from the row it was supposed to be below.

None of the other solutions I have seen around this seem to take account of 
this sorting problem.

I saw one solution hinted at somewhere, where you add an extra column 
called, say, "Order", and fill in values that number the rows in the 
current correct sorted order (including the new row you are adding), then 
re-sort on Order. That seems to almost work (though not entirely) but it 
causes a big problem in determining which rows have been modified and need 
to be saved, because every row is modified by setting the Order column's 
value!

Any bright ideas? Thanks.

---------------------------
Dan Cooperstock
DONATION web site:  http://www.**--****.com/ 
DONATION Support forums:  http://www.**--****.com/ 
E-mail: mailto: XXXX@XXXXX.COM 
Home Phone: 416-423-9064

Re: Inserting row into user sorted, data-bound DataGridView

Postby RB » Fri, 15 Jun 2007 00:39:41 GMT

Consider what the maximum number of donations for an indivisual is likely to 
be and add a <Sequence> field to your table.  The sequence will start at 100 
for that each donor's first contribution so, each record picks up this value 
for the initial entry of the record.  Updates are still updates and not 
inserts.

Your sort will be a dual sort of column name, sequence.

If you discover that you have missed a sequence and need to instert on 
mid-sequence, you have 99 tries to do it.

The new sequence field should never need to be updated based on a column 
header sort.


BTW:
If you are using mouse up/down events to trap your column sort, how do you 
reference the column name?  I am using the following that works but wonder 
if there is a better way.

columnName = 
Me.OrdersTableStyleDataGridTableStyle.GridColumnStyles(i).MappingName

RB
-- 
remove underscore to send me mail, no spam







Re: Inserting row into user sorted, data-bound DataGridView

Postby Dan Cooperstock » Fri, 15 Jun 2007 02:33:04 GMT

Unfortunately, my DGV is listing donations for all donors. So, the sort 
(based on clicking on column headers) might be on the Amount of the 
donation, across all donors. No sort using a new sequence number field 
will put a new row right below the current row, when they are sorted by 
amount.

In answer to your question, Robert, currently I'm not catching the 
ColumnHeaderClick event which is what triggers the sort, I'm just letting 
the sorts happen automatically. But I think in that event it is easy to 
find out which column was clicked.

"RB" < XXXX@XXXXX.COM > wrote in






-- 
---------------------------
Dan Cooperstock
DONATION web site:  http://www.**--****.com/ 
DONATION Support forums:  http://www.**--****.com/ 
E-mail: mailto: XXXX@XXXXX.COM 
Home Phone: 416-423-9064

Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Fri, 15 Jun 2007 16:29:16 GMT

Hi Dan,

Based on my understanding, you have a data bound DataGridView and want to 
add a similar row to the current selected row into the DataGridView and 
right after this row when you click a button on the form. If I'm off base, 
please feel free to let me know.

Firstly, we couldn't add a row into a DataGridView programmatically if the 
DataGridView is bound to a data source. So we have to add the new row into 
the data source. To get the newly added row to appear near the 'copied' 
row, we could sort the DataGridView by the particular column, in your case, 
the donor name column.

You may use BindingSource as the data source, i.e. bind the BindingSource 
to a DataSet and a DataTable in it and then bind the DataGridView to the 
BindingSource. To sort on a column, set the Sort property of the 
BindingSoure  to the column's name. 

The following is a sample. It requires to add a DataGridView and a Button 
on the form.

 private void Form1_Load(object sender, EventArgs e)
        {          
            BindingSource bs = new BindingSource(this.dataSet11, 
"DataTable1");
            this.dataGridView1.DataSource = bs;         
            // fill data into the data source
            DataSet1TableAdapters.StudentTableAdapter ta = new 
WindowsMediaPlayer.DataSet1TableAdapters.DataTable1TableAdapter();
            ta.Fill(this.dataSet11.DataTable1);
        }

private void button1_Click(object sender, EventArgs e)
        {
            DataRowView drv = this.dataGridView1.CurrentRow.DataBoundItem 
as DataRowView;

            if (drv != null)
            {
                DataRow row = this.dataSet11.DataTable.NewRow();
                // the first field is the primary key
                row[0] = some unique id ;
                row[1] = drv[1];
                row[2] = drv[2];
                this.dataSet11.Student.Rows.Add(row);
                (this.dataGridView1.DataSource as BindingSource).Sort = 
"ColumnName";
            }                    
        }

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to 
 http://www.**--****.com/ #notif
ications.
 
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues 
where an initial response from the community or a Microsoft Support 
Engineer within 1 business day is acceptable. Please note that each follow 
up response may take approximately 2 business days as the support 
professional working with you may need further investigation to reach the 
most efficient resolution. The offering is not appropriate for situations 
that require urgent, real-time or phone-based interactions or complex 
project analysis and dump analysis issues. Issues of this nature are best 
handled working with a dedicated Microsoft Support Engineer by contacting 
Microsoft Customer Support Services (CSS) at 
 http://www.**--****.com/ 
==================================================
 
This posting is provided "AS IS" with no warranties, and confers no rights.


Re: Inserting row into user sorted, data-bound DataGridView

Postby Dan Cooperstock » Fri, 15 Jun 2007 20:36:23 GMT

nfortunately, that's close but not close enough to what I'm trying to
do. And I did already know how to do that much.

I am allowing the user to sort the DGV on any column, such as the Amount
column (by clicking on column headers). Then I need the inserted row to
appear right below the selected row, maintaining the current sort order
except for the order of the new row being exactly where I want it. That
doesn't happen if the current sort is on anything other than the Name
column.

I am quickly coming to the conclusion that what I want is impossible,
under my requirements and the current .NET API. I'm thinking that I
should just add the row (e.g. at the end), let it sort where the current
DGV's sort puts it, then use Find on the DataView to find it and position
to it. If the current sort is on the Name, this will give exactly what I
want. If it isn't, the new row will be separated from the original row,
but I least I can give the user a message explaining that this has
happened because the sort isn't on the Name.

Any better ideas?

XXXX@XXXXX.COM (Linda Liu [MSFT]) wrote in
news: XXXX@XXXXX.COM :



--
---------------------------
Dan Cooperstock
DONATION web site: http://www.FreeDonationSoftware.org
DONATION Support forums: http://forums.FreeDonationSoftware.org
E-mail: mailto: XXXX@XXXXX.COM
Home Phone: 416-423-9064

Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Sat, 16 Jun 2007 21:50:31 GMT

Hi Dan,

I am busy today so I haven't got a chance to research on this issue.

In addition, I will be OOF on the next Monday and Tuesday, so I will reply 
to you on the next Wednesday.

Sorry for the delay!

Have a nice weekend!

Sincerely,
Linda Liu
Microsoft Online Community Support


Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Thu, 21 Jun 2007 20:09:25 GMT

Hi Dan,

Thank you for your prompt response.

Since you'd like to customize sorting in the DataGridView, I suggest that 
you handle the SortCompare event of the DataGridView for your practice. You 
may refer to the following MSDN document for a sample of custom sorting 
using the SortCompare event, as well as other methods for custom sorting:

'How to: Customize Sorting in the Windows Forms DataGridView Control'
 http://www.**--****.com/ 

Hope this helps.
If you have any question, please feel free to let me know.


Sincerely,
Linda Liu
Microsoft Online Community Support


Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Sat, 23 Jun 2007 20:11:49 GMT

Hi Dan,

How about the problem now?

If you need our further assistance, please feel free to let me know.

Thank you for using our MSDN Managed Newsgroup Support Service!

Sincerely,
Linda Liu
Microsoft Online Community Support


Re: Inserting row into user sorted, data-bound DataGridView

Postby R2lv » Thu, 28 Jun 2007 00:33:11 GMT

Sorry Linda and Dan if I interposing me around this thread but I also 
troubling about DataGridView sort. I trying (I think like Dan) to disable 
automatic sort during adding data into a datagridview without success !!!

I creating a more or less complex structure which allows to sort,  search, 
update, insert datas into a DB table through a DataGridView (also above 
master DGV is linked to a detail DGVs in order to populate information 
related to detail tables).

So, my problem is that I want preserve all new rows added in the original 
position  and to trigger DGV sort on demand (e.g. after right commit) . It 
because my form check all data consistence during save data (by event 
handler) and due to the fact that utomatic sortspreads all new rows 
inside DGV (after each insert),  if error raised, I have to search where the 
new rows are.

So, keep in mind that I already read s171608.aspxand it seams that there 
isn into it solution at my problem. Also, keep in mind that I tried to 
handling utomatic sortby verrideof the class 
ataGridViewColumnHeaderCell(in order to handle{*filter*} on header column 
. For that I set ataGridViewColumnSortModeto rogrammatic(also I tried 
otSortablewith the same result) in order to manage GV.Sortmethod into 
my class.

It works right just until irst clickon header column (because ortMode
property disabled all). But after that, DGV (seams) captures ort method
and it restarts rows spreads again, as usual.

So, is it a bug ? Above is the right way to manage a sort via rogrammatic
status ,  isn it ?

Many Thanks for answer.





>
>>Hi Dan,
> 
> How about the >rob>em now?
> 
> If you need our further assistance, please feel free to >et >e know.
> 
> Thank you for using our MSDN Managed Newsgroup Supp>rt >ervice!
> 
> Microsoft Online Commu>ity>Support

Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Thu, 28 Jun 2007 17:29:24 GMT

Hi Gio,

I performed a test based on your description but didn't reproduce the 
problem on my side.

I add two DataGridViewTextBoxColumns in a DataGridView and set the SortMode 
property of the two DataGridViewTextBoxColumns to Programmatic. I run the 
application and no matter how many times I click on the header column, not 
sorting happens. 

You may have a try adding a standard DataGridViewTextBoxColumn in the 
DataGridView and set the column's SortMode property to Programmatic to see 
if the problem still exists.

Sincerely,
Linda Liu
Microsoft Online Community Support


Re: Inserting row into user sorted, data-bound DataGridView

Postby R2lv » Thu, 28 Jun 2007 23:04:19 GMT

i Linda,
first of all, thanks for replay.

In order to reproduce my same result, in my opinion you have to try to do
following:

First of all, you haven to change the ortModeproperties on DGV
(preserve the standard value which is utomatic
After that:

- run your application
- click on the header column that you want to sort
- put in new rows

You will can see that for each new row inserted, DGV will spread new row
inside it in the right order (based on column clicked)
So, up to this point, I think we are using DVG in standard way

After that you try to personalize ortmode in order to handle it. To do
that I have implemented following (sorry, I using c# language)

1) Create into your application a custom class like following:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace WindowsApplication1
{
class Class1 : DataGridViewColumnHeaderCell
{
private DataGridView _dgv;
private ListSortDirection _sortdir;

public Class1(DataGridView dgv)
{
_dgv = dgv;
}
protected override void OnClick(DataGridViewCellEventArgs e)
{
base.OnClick(e);

//Set Sort Direction
if (_dgv.SortOrder == SortOrder.Ascending)
{
_sortdir = ListSortDirection.Descending;
}
else
{
_sortdir= ListSortDirection.Ascending;
}
//Run Sort Method
_dgv.Sort(_dgv.Columns[e.ColumnIndex], _sortdir);
_dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection =
_sortdir == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;

}
}
}


2) Add into Form1 constructor, following code (where tabella1DataGridView
is your DGV):

public partial class Form1 : Form
{
string txth;
public Form1()
{
InitializeComponent();
foreach (DataGridViewColumn c in
this.tabella1DataGridView.Columns)
{
txth = c.HeaderCell.Value.ToString();
c.SortMode = DataGridViewColumnSortMode.Programmatic;
c.HeaderCell = new Class1(this.tabella1DataGridView);
c.HeaderCell.Value = txth;
}
}
€ € ..

3) Run your application and:
- put into new rows (without click on header) . In this case, DGV will
preserve insert line position.
- click on header in order to trigger sort column
- put new row again

For the second session of insert, DGV will start again the row spreads.

So, I have re-created utomatic sortstandard way.

I supposed that via rogrammaticmode I can handle the ort methodon
demand (sort run only by click on the header). But it seems I supposing a
wrong way.
I have recreated via rogrammaticmode the same utomaticbehaviour mode
(keep in mind that with SortMode=NotSorted is the same..

Is there a way to maintain the ortready but stop it during data add ?

My question is based on the fact that in some cases, in my opinion, it is
quite well having also a possibility to maintain all new rows inserted,
there, in order to can see those, and to trigger spreads by sort eventually
after save (if DGV contain a lot of rows, I can lose immediate visibility on
new. It depending on sort va

Re: Inserting row into user sorted, data-bound DataGridView

Postby v-lliu » Sat, 30 Jun 2007 20:48:37 GMT

Hi Gio,

I performed some tests based on your description and did reproduce the 
problem.

In my tests, the problem exists only when the DataGridView's bound to a 
data source. 

In fact, if the DataGridView is bound to a data source, when we call the 
DataGridView.Sort method to sort the grid programmatically, the sort is 
actually done by the underlying data source. 

Then the sort is maintained in the underlying data source. Any new data 
added into the data source after this will be shown in a 'proper' position 
in the DataGridView.

I suggest that you use BindingSource as the data source and call the 
RemoveSort method to remove the sort when you add new data in the data 
source.

Hope this helps.

Sincerely,
Linda Liu
Microsoft Online Community Support


Re: Inserting row into user sorted, data-bound DataGridView

Postby R2lv » Sat, 30 Jun 2007 22:56:04 GMT

Dear Linda,

I testing your suggestion and it seems is working right (I searched a 
method able to remove sort from DGV and, really, I did not see that it was 
there, under my nose !!!).

Thank you very much for your help.

Sincerely.
Gio


Similar Threads:

1.Allow user to add/del rows not possible with data bound DataGridView

Hello,

I have a DataGridView control that I bound to an array of objects. This
works fine but now the properties AllowUserToAddRows and
AllowUserToRemoveRows have no effect anymore, which means no empty row
for adding new rows is displayed and pressing Del on an existing row
does not delete the row. Without databinding, this worked fine.

What am I doing wrong?


Jens

2.DataGridView creates too many new rows when inserting new data

3.Adding Rows to Data-Bound DataGridView

A data-bound DataGridView is wonderfully simple to include with a Windows Form.

Now that all the data is there, how do I go about adding a new record? When 
I tried, Visual Studio 2005 Pro gave me an InvalidOperationException, saying, 
"Rows cannot be programmatically added to the DataGridView's rows collection 
when the control is data-bound."

Am I just not able to add a new record ever if I use a data-bound 
DataGridView, or do I need to follow some special steps to un-data-bind it, 
add my data, then re-data-bind it?

4.Data-bound DataGridView creates bogus empty rows

Hello. I have a DataGridView that is bound to a DataTable. If the user
types in values for all the columns for the first row, then clicks
into a column in the second row (empty), and then clicks back into the
first row he just typed, then an empty row is added to the
DataGridView. I'm guessing that somehow the AddRow function is being
called when the user clicks in and out of the empty row. I don't want
this to happen. A new row should only be added to the DataGridView if
the user types in valid values for all the columns. Does anyone know
how to fix this? Thanks.

Justin

5.DataGridView/BindingSource - new row position (IsCurrentRowDirty is false) causes data binding issue

Hi,

I have a DataGridView linked with a BindingSource. I edit an existing
row and then commit the edit by moving onto the new row position. Then
I click on a save button that runs some code to update the database.
Here's the crux of that code:

BindingServices.EndEdit(); // BindingSource
ServicesAdapter.Update( Database );
Database.AcceptChanges(); // DataSet

The problem happens on the EndEdit line - it causes .NET to complain
about a field that has been set in the typed DataSet as mandatory
(referring to the record in the new row position that has no data
entry). If I comment out the EndEdit line, the code works (except that
the GridView displays a new blank row and then complains about the
mandatory field as soon as you move off it). Should the DataGridView
behave like this?

Upon further investigation I found out that when the user clicks on
the new row position, it creates a detached row. From a databinding/
user interface point of view, I can see that this makes sense. But why
is it included in the DataTable when I do an EndEdit if it's detached?
I can use the following code to disable the detached row:

if ( ServicesGrid.CurrentRow.IsNewRow )
	ServicesGrid.CancelEdit();

But then (of course) the current position of the BindingSource changes
- changing the position in the DataGridView. Potentially, this could
be confusing to the end user.

So, is there a better way to deal with this, or am I just missing
something?

Thanks,

Camel

6. DatagridView, Data Binding, New Row

7. DataGridView, Data Binding, New Row.

8. Adding rows to a bound table that is bound to DataGridView(DataSou



Return to dotnet framework

 

Who is online

Users browsing this forum: No registered users and 43 guest