Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Windows Forms / WinForm Controls / December 2007

Tip: Looking for answers? Try searching our database.

Reordering rows in DataGrid cause wrong value selected in ComboBox

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Paul S - 06 Dec 2007 20:06 GMT
Hi

I have a DataGrid with 2 columns and one of them is a ComboBoxColumn. I have
implemented re-ordering of rows as described in
windowsclient.net/samples//Go%20To%20Market/DataGridView/DataGridView%
If I have selected a value in the ComboBoxColumn and then move that row to a
new position then the selected value in the ComboBoxColumn is not shown.
Instead the underlying datatype - System.Data.DataRow - is shown. How can I
fix that ?

LookupTable is a DataTable. The 2 most relevant methods are listed below.

       private void Form1_Load(object sender, EventArgs e)
       {
           this.dataGridView1.RowCount = 3;

           DataColumn col = new DataColumn("ID", typeof(Int32));
           this.LookupTable.Columns.Add(col);
           col = new DataColumn("Name", typeof(string));
           this.LookupTable.Columns.Add(col);
           DataRow row = this.LookupTable.NewRow();
           row[0] = 1;
           row[1] = "aa";
           this.LookupTable.Rows.Add(row);
           row = this.LookupTable.NewRow();
           row[0] = 2;
           row[1] = "bb";
           this.LookupTable.Rows.Add(row);

           DataGridViewComboBoxColumn c = this.dataGridView1.Columns[0] as
DataGridViewComboBoxColumn;
           if (null == c)
               return;
           // bind the DataGridViewComboBoxColumn to the DataTable
           (this.dataGridView1.Columns[0] as
DataGridViewComboBoxColumn).DataSource = this.LookupTable;
           (this.dataGridView1.Columns[0] as
DataGridViewComboBoxColumn).ValueMember = "ID";
           (this.dataGridView1.Columns[0] as
DataGridViewComboBoxColumn).DisplayMember = "Name";

       }

       private void dataGridView1_DragDrop(object sender, DragEventArgs e)
       {
           // The mouse locations are relative to the screen, so they must
be
           // converted to client coordinates.
           Point clientPoint = this.dataGridView1.PointToClient(new
Point(e.X, e.Y));

           // Get the row index of the item the mouse is below.
           rowIndexOfItemUnderMouseToDrop =
               this.dataGridView1.HitTest(clientPoint.X,
clientPoint.Y).RowIndex;

           // If the drag operation was a move then remove and insert the
row.
           if (e.Effect == DragDropEffects.Move)
           {
               DataGridViewRow row =
e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;
               try
               {
                   DataRow rowToMove = this.LookupTable.Rows[row.Index];
                   DataRow newRow = this.LookupTable.NewRow();
                   newRow.ItemArray = rowToMove.ItemArray;

                   this.LookupTable.Rows.RemoveAt(row.Index);
                   this.LookupTable.Rows.InsertAt(newRow,
rowIndexOfItemUnderMouseToDrop);
                   
                   
dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

                   this.dataGridView1.Refresh();
               }
               catch (Exception ex)
               {
                   
System.Diagnostics.Trace.WriteLine("dataGridView1_DragDrop failed: " +
ex.ToString());
               }
           }
       }

Signature

Paul S

Linda Liu[MSFT] - 07 Dec 2007 03:48 GMT
Hi Paul,

I notice that you may mistake DataRow in the Lookup table with the
DataGridViewRow in the DataGridView in the following lines of code, which
are not the same thing:

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
   ...
     try
               {
                   DataRow rowToMove = this.LookupTable.Rows[row.Index];
                   DataRow newRow = this.LookupTable.NewRow();
                   newRow.ItemArray = rowToMove.ItemArray;

                   this.LookupTable.Rows.RemoveAt(row.Index);
                   this.LookupTable.Rows.InsertAt(newRow,
rowIndexOfItemUnderMouseToDrop);
                   
                   
dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

                   this.dataGridView1.Refresh();
               }
          ....
}

You should remove the DataGridViewRow being dragged from the DataGridView
first and insert this DataGridViewRow into the new index. Modifiying the
above code as follows should solve the problem:

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
   ...
     try
               {
                    this.dataGridView1.Rows.Remove(row);
                   
this.dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, row);
               }
       ....
}

If the problem is still not solved, please send me a simple project that
could just reproduce the problem. To get my actual email address, remove
'online' from my displayed email address.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#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://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Paul S - 07 Dec 2007 12:20 GMT
Hi Linda
That works.
Just to point out what did it, compared to the FAQ, where I got the original
solution from - the difference is:

dataGridView1.Rows.Remove(gridRowToMove); // works
//dataGridView1.Rows.RemoveAt(rowIndexOfItemUnderMouseToDrop); does not work.

When I started moving the rows around I had errors with an uncommitted row.
This happened when I moved the last row or when I moved a row below the last
one.
I my case I could solve this by:

           this.dataGridView1.AllowUserToAddRows = false;
           this.dataGridView1.AllowUserToDeleteRows = false;

The root of the problem was the last un-commited row added by the grid when
the user was allowed to add rows.

Thanks again Linda.
Signature

Paul S

Paul S - 07 Dec 2007 13:19 GMT
I works as I wrote in my last mail, but when the control is databound
I get the error:

Rows cannot be programmatically added to the DataGridView's rows collection
when the control is data-bound.

Signature

Paul S

Linda Liu[MSFT] - 10 Dec 2007 02:54 GMT
Hi Paul,

Thank you for your reply!

> The root of the problem was the last un-commited row added by the grid
when the user was allowed to add rows.

Yes, you're right. We cannot remove the new row or insert a DataGridViewRow
after the new row in a DataGridView. As you said, the solution is to set
the AllowUserToAddRows property of the DataGridView to true.

> I works as I wrote in my last mail, but when the control is databound I
get the error:

No, we cannot add or remove a DataGridViewRow programmtically to a
DataGridView when this DataGridView is data-bound. To do this, you may
exchange the rows in the underlying data source instead. The following is a
sample:

DataRow row = dataTable1.Rows[0];
DataRowState rowstate = row.RowState;
object[] itemarray = row.ItemArray;
 dataTable1.Rows.Remove(row);
 row.ItemArray = itemarray;

 this.LookupTable.Rows.InsertAt(row, 1);
 if (rowstate == DataRowState.Added)
  {
        row.SetAdded();
  }
  else if (rowstate == DataRowState.Modified)
  {
       row.SetModified();
  }
  else if (rowstate == DataRowState.Unchanged)
  {
        row.AcceptChanges();
  }

Hope this helps.
If you have anything unclear, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support
Linda Liu[MSFT] - 10 Dec 2007 02:56 GMT
Hi Paul,

Sorry that I made a mistake in my previous reply.

The line of code
this.LookupTable.Rows.InsertAt(row, 1);
should be
dataTable1.Rows.InsertAt(row, 1);


Sincerely,
Linda Liu
Microsoft Online Community Support
Paul S - 10 Dec 2007 07:17 GMT
Hi Linda

At first I couldn't get it to work - then I deleted the part I didn't
understand - the RowState stuff - now it seems to work and it looks like this:

       private void dgvLookup_DragDrop(object sender, DragEventArgs e)
       {
           // The mouse locations are relative to the screen, so they must
be
           // converted to client coordinates.
           Point clientPoint = this.dgvLookup.PointToClient(new Point(e.X,
e.Y));

           // Get the row index of the item the mouse is below.
           rowIndexOfItemUnderMouseToDrop =
               this.dgvLookup.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

           // If the drag operation was a move then remove and insert the
row.
           if (e.Effect == DragDropEffects.Move)
           {
               DataGridViewRow gridRow =
e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;

               DataRow rowToMove = dataTable1.Rows[gridRow.Index];
               object[] itemarray = rowToMove.ItemArray;
               dataTable1.Rows.Remove(rowToMove);
               rowToMove.ItemArray = itemarray;

               dataTable1.Rows.InsertAt(rowToMove,
rowIndexOfItemUnderMouseToDrop);
           }
       }

Signature

Thanks a lot again Linda.
Paul S


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.