0
votes

I fill a DataGridView from a datatable. And I use the selectionchanged event in the DataGridView control.

When I insert a new item into the database and reload datatable in the grid, it selects the first row in the datagridview by default.

How can I select the last row which was inserted into the DataGridView?

4

4 Answers

0
votes

Try this

dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
0
votes

I've created a dummy project for you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestApplications
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public class foo
    {
        public foo()
        {
            ID = Count + 1;
        }
        public static int Count;
        public int ID { get; set; }
        public string Name { get; set; }
    }

    List<foo> x = new List<foo>();
    foo LastSelectedItem = new foo();

    public MainWindow()
    {
        InitializeComponent();
        this.btnAdd.Click += new RoutedEventHandler(btnAdd_Click);
        this.dgvItems.SelectionChanged += new SelectionChangedEventHandler(dgvItems_SelectionChanged);
    }

    void dgvItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if(((DataGrid)sender).SelectedItem != null)
            LastSelectedItem = ((DataGrid)sender).SelectedItem as foo;
    }

    void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        if (txtItemContent.Text.Trim().Length != 0)
        {
            foo item = new foo();
            foo.Count = foo.Count + 1;
            item.Name = txtItemContent.Text;
            x.Add(item);
            dgvItems.ItemsSource = null;
            dgvItems.ItemsSource = x;
            dgvItems.SelectedItem = LastSelectedItem;
        }
    }


}
}

Then this code below for the XAML If you're using WPF or Silverlight.(Disregard it if you are using winforms I've just showed it for you that an idea on what am i calling in the code)

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="TestApplications.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="27"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <DataGrid x:Name="dgvItems" Grid.Row="1" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="ID" Binding="{Binding ID}" Header="ID"/>
            <DataGridTextColumn x:Name="Name" Binding="{Binding Name}" Header="Name" Width="460"/>
        </DataGrid.Columns>
    </DataGrid>
    <StackPanel Orientation="Horizontal" d:LayoutOverrides="Width" HorizontalAlignment="Left">
        <Label Content="Item:" d:LayoutOverrides="Height"/>
        <TextBox x:Name="txtItemContent" TextWrapping="Wrap" VerticalAlignment="Center" MinWidth="250"/>
        <Button x:Name="btnAdd" Content="ADD" Margin="0" Width="75" VerticalAlignment="Center"/>
    </StackPanel>
</Grid>

0
votes

Assuming you have atleast one column you try setting the currentcell of the grid

dataGridView1.CurrentCell = dataGridView1[0,dataGridView1.Rows.Count - 1];
0
votes

you can try like this....

private void ReloadDgv(int id)
{
  // id should be the your record id 
  // This is to set forcus on change record or new record
  RefeshDgv();
  if(condition you are adding new record to datagrid view)
    dgv.Rows[dgv.Rows.Count - 1].Selected = true;

  else if (id > 0)(you are updating present record)
  {
    var i = 0;
    foreach (DataGridViewRow row in dgv.Rows)
    {
      if ((int)row.Cells[0].Value == id)
      {
        dgv.Rows[i].Selected = true;
        break;
      }
      i++;
    }
  }
}



private void RefeshDgvStaff()
{
  if (_obj.getGridViewData().DataSource != null)
  {
    dgv.DataSource = _obj.getGridViewData();  // where i am binding the datagird view ...
    dgvSetHeaders();
  }
}

you have to call the reloaddgv(id)

 public void savefunction()
 {
     // where do u insert the records into database
        reloaddgv(0);

  }