Set currentRow in dgv

  • Thread starter Thread starter dbuchanan
  • Start date Start date
D

dbuchanan

Hello,

I have set my dgv to MultiSelect = False and SelectionMode = FullRowSelect.
How to I programatically make a specific row current?

Additional detail relevent to what I am trying to do...
When the user has a specific row selected and clicks the edit button a
dedicated edit form opens. After completing and saving the edit that form
closes and the dgv on the main form refreshes (fill again). Therefore the
selected row is lost to the user. I want the slection to be preserved for
the user. How do I do this?


My current code...

private int pkMTaskIdDgvMTasksCurrentRow()
{
return (int)dgvMTasks.CurrentRow.Cells[0].Value;
}

private void btnAddViewEditTasks_Click(object sender, EventArgs e)
{
//Open with the desired value
AddEditMasterTask f = new
AddEditMasterTask(pkMTaskIdDgvMTasksCurrentRow());
f.ShowDialog();
taVwMTask_PhaseDimUnit2.Fill(dataSetHipAdmin2.vwMTask_PhaseDimUnit2);
// code here to set the current row back to what it was
}

Thank you,
Doug
 
Hi Doug,

Once you know the row index, you may use
DataGridView.Rows[row_index].Selected = true.

To get the previous editing row, you may first save the old selected row
position and re-select in future. The code below demonstrates this logic:

//Save the old position
CurrencyManager cm = this.dataGridView1.BindingContext[this.dt] as
CurrencyManager;
if (cm != null)
{
int oldPosition = cm.Position;
}

//Restore the old position
CurrencyManager cm = this.dataGridView1.BindingContext[this.dt] as
CurrencyManager;
if (cm != null)
{
cm.Position = oldPosition ;
}

Note: this code only works for the editing scenario. If your code may also
delete or add the rows, you should use the code above. You should search
the primary key in the DataGridView to find the DataGridViewRow and select
it.

Hope this helps.

Best regards,
Jeffrey Tan
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.
 
Hi Jeffrey

The following selects the row but does not make it current. This will not
work for me.
=============
private void btnAddViewEditTasks_Click(object sender, EventArgs e)
{
//Save the old position
int rowIndex = this.dgvMTasks.CurrentRow.Index;
AddEditMasterTask f = new
AddEditMasterTask(pkMTaskIdDgvMTasksCurrentRow());
f.ShowDialog();
taVwMTask_PhaseDimUnit2.Fill(dataSetHipAdmin2.vwMTask_PhaseDimUnit2);
//Restore the old position
this.dgvMTasks.Rows[rowIndex].Selected = true;
}
=============

I need to set the Current row not the slected row. There is a difference I'm
sure you know.

http://groups.google.com/group/micr...gst&q=set+current+row&rnum=6#b3922a8a5db13e70

but I can't find how to set it. Can you tell me how that is done?

Maybe I didn't understand but this does not work. It does not resore the
current postion of the selected/current row.
=============
private void btnAddViewEditTasks_Click(object sender, EventArgs e)
{
//Save the old position
CurrencyManager cm =
this.dgvMTasks.BindingContext[dataSetHipAdmin2] as CurrencyManager;
int oldPosition = cm.Position;
AddEditMasterTask f = new
AddEditMasterTask(pkMTaskIdDgvMTasksCurrentRow());
f.ShowDialog();
taVwMTask_PhaseDimUnit2.Fill(dataSetHipAdmin2.vwMTask_PhaseDimUnit2);
//Restore the old position
cm.Position = oldPosition;
}
=============
Would you help.

It is like the authors of help could not use any imagination that someone
would ever what to do that --- or I don't know how to find such things form
help.

Thank you,
Doug
 
Hi Doug,

Thanks for your feedback.

In MultiSelect = False and SelectionMode = FullRowSelect, I think the
current row should be the same as selected row. Anyway, if you wanted to
set the current row, you may set DataGridView.CurrentCell to one cell of
that row. This will set the current row either.

Regarding setting the CurrencyManager.Position not working, I have written
a test project with code below. Button1 saves the old position and the
Button2 will restore the old postion, it works well on my side:

DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("column1", typeof(int)));
dt.Columns.Add(new DataColumn("column2", typeof(string)));

for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["column1"] = i;
dr["column2"] = "item" + i.ToString();
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
}

int oldPosition;
private void button1_Click(object sender, EventArgs e)
{
CurrencyManager cm = this.dataGridView1.BindingContext[this.dt] as
CurrencyManager;
if (cm != null)
{
oldPosition = cm.Position;
}
}

private void button2_Click(object sender, EventArgs e)
{
CurrencyManager cm = this.dataGridView1.BindingContext[this.dt] as
CurrencyManager;
if (cm != null)
{
cm.Position = oldPosition;
}
}

If you still fail to get it working, I can provide a sample project to you.
Thanks.

Best regards,
Jeffrey Tan
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.
 
Jeffery,
In MultiSelect = False and SelectionMode = FullRowSelect, I think the
current row should be the same as selected row.

It IS set MultiSelect = False and SelectionMode = FullRowSelect
but it does not work. Here is my code again.

=============
private void btnAddViewEditTasks_Click(object sender, EventArgs e)
{
//Save the old position
CurrencyManager cm =
this.dgvMTasks.BindingContext[dataSetHipAdmin2] as CurrencyManager;
int oldPosition = cm.Position;
AddEditMasterTask f = new
AddEditMasterTask(pkMTaskIdDgvMTasksCurrentRow());
f.ShowDialog();
taVwMTask_PhaseDimUnit2.Fill(dataSetHipAdmin2.vwMTask_PhaseDimUnit2);
//Restore the old position
cm.Position = oldPosition;
}
=============

Thank you for your sample code. There are differences in my code and yours,
but not differences that I think should cause it not to work.
Your buttons recreate the currency manager, mine reuses the curencymanager
variable because I go to a dialog, but that shouldn't make the variable not
work. It does not throw an error.

....
I don't think it is possible to do what I want to do!

What I am trying to do:
When the user has a specific row selected in the dgv and clicks the edit
button a
dedicated edit form opens. After completing and saving the edit that form
closes and the dgv on the main form refreshes (fill again). Therefore the
selected row is lost to the user. I want the slection to be preserved for
the user.

Her is why I don't think this is possible
.. If the user adds a row - the code will not know which row to make current
because the ID is assigned by the database
.. If the user deletes a row - the code will not know where to go. I would
probably want to go to a the previous record.
.. If the user edits a row it cannot reliably return to that row based on
currentCell because the row must be unique to be reliable and the only
unique column is the hidden primary key in my form ( I would have to show
it)

It looks like I don't have many choices but show the primay key, yet that
only fixes one of the three in my list.

Can you think on anything?

Is there any way to refresh the edited data without clearing and refilling
the datagrid?

Thank you,
Doug
 
Hi Doug,

Thanks for your detailed feedback.
Your buttons recreate the currency manager
Not exactly, my code did not create a new CurrencyManager. The
CurrencyManager object is always maintained in the databinding manager, in
my second button, I just retrieve the original CurrencyManager through
reference. I did not create a new one. So my code logic should be the same
as yours.

Yes, I agree that we may not go with the solution of setting
CurrencyManager.Position, since you may add or delete rows.

I think your requirement is possible, here is the logic:
Before you edit(add) the rows, you may first preserve the selected
row(current row) primary cell value. After the editing(adding), you may
search in the DataGridView for the original saved primary cell value. Once
you find that cell, you may set it as the DataGridView.CurrentCell.

Regarding the deleting scenario, you have to save the previous row primary
cell value.

Does this logic meet your need? If not, please feel free to explain to me.
Thanks.

Best regards,
Jeffrey Tan
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.
 
Hello Jeffry,
Does this logic meet your need?
Yes. I would have to show the primary key id, but I guess that is okay.
After the editing(adding), you may search in the DataGridView
for the original saved primary cell value. Once you find that cell,
you may set it as the DataGridView.CurrentCell.

I think I know how to do this... (from viewing a post by Linda Lu)

// find the row
int gridrowindex = this.bindingSource1.Find("MyPrimaryKeyColumn", "11");

// set the current cell
this.dataGridView1.CurrentCell = DataGridViewCell(gridrowIndex,1)

Have you done this before? Do you have any suggestions?

Thanks,
Doug
 
Thanks Jeffery,

With your help and after a little work I figured out how to get and set the
CurrentCell of a data bound DataGridView.

My first column (Cells[0]) is the primary key of the bound data. I put two
buttons on my form to Save and Restore the column position in this test.

=== When the DataGridView is Bound ===

// variable to save the bound value of the primary key
string pk;

private void btnSaveCurrentRow_Click(object sender, EventArgs e)
{
// Save the primary key value
pk = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
//MessageBox.Show(pk);
}

private void btnRestoreCurrentRow_Click(object sender, EventArgs e)
{
// Find the primary key value in the bindingSource
int gridrowindex = this.bindingSource1.Find("pkPhaseID", pk);
// Restore the cursor position
this.dataGridView1.CurrentCell =
this.dataGridView1.Rows[gridrowindex].Cells[0];
}


Thanks,
Doug
 
Hi Doug ,

Sorry for the late reponse, I am taking sick leave at home yesterday.

Thank you for updating your status. Yes, this logic should work.
Additionally, there is no need for you to show the primary key column in
the DataGridView. When you save the editing row primary key value, you may
use CurrencyManager.Current to get the DataRowView of that row. Then you
may get the primary key value in the DataRowView.

If you have problem of getting the above logic to work, please feel free to
tell me, thanks.

Best regards,
Jeffrey Tan
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.
 
Jeffery,
Additionally, there is no need for you to show the primary key column in
the DataGridView. When you save the editing row primary key value, you may
use CurrencyManager.Current to get the DataRowView of that row. Then you
may get the primary key value in the DataRowView.

Thank you for that tip. I didn' t think it was possible.

With a little thought and work I arrived at the code below.

Because 'CurrentRow' cannot set its value when hidden I didn't think it
could get its value when it was hidden either, but it can as the working
code below demonstrates. Pleasant surprise!

// variable to save the bound value of the primary key
string pk;

private void btnSaveCurrentRow_Click(object sender, EventArgs e)
{
// Save the primary key value
pk = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
//MessageBox.Show(pk);
}

private void btnRestoreCurrentRow_Click(object sender, EventArgs e)
{
// Find the primary key value in the bindingSource
int gridrowindex = this.bindingSource1.Find("pkPhaseID", pk);
// Restore the cursor position
this.dataGridView1.CurrentCell =
this.dataGridView1.Rows[gridrowindex].Cells[1];
}

Thank you,
Doug
 
Back
Top