【问题标题】:Selecting a row in DataGridView在 DataGridView 中选择一行
【发布时间】:2011-10-28 03:07:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: datagridview c#-3.0 selectionchanged


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

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

      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 代码。(如果您使用的是 winforms,请忽略它,我刚刚向您展示了我在代码中调用了什么的想法)

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          你可以这样试试....

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-10
            • 2012-08-10
            • 1970-01-01
            相关资源
            最近更新 更多