在 DataGridView 中选择一行

发布于 2024-12-12 08:09:48 字数 168 浏览 0 评论 0原文

我从数据表填充 DataGridView。 我在 DataGridView 控件中使用 SelectionChanged 事件。

当我将新项目插入数据库并在网格中重新加载数据表时, 它默认选择 datagridview 中的第一行。

如何选择插入到 DataGridView 中的最后一行?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鱼窥荷 2024-12-19 08:09:48

试试这个

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

Try this

dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
触ぅ动初心 2024-12-19 08:09:48

我为你创建了一个虚拟项目。

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;
        }
    }


}
}

如果您使用的是 WPF 或 Silverlight,则下面的 XAML 代码。(如果您使用的是 winform,请忽略它,我刚刚向您展示了我在代码中调用的内容的想法)

<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>

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>

入怼 2024-12-19 08:09:48

假设您至少有一列,您尝试设置网格的当前单元格

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

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

dataGridView1.CurrentCell = dataGridView1[0,dataGridView1.Rows.Count - 1];
独享拥抱 2024-12-19 08:09:48

你可以这样尝试......

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();
  }
}

你必须调用 reloaddgv(id)

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

  }

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);

  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文