【问题标题】:datagridview values disappear after i close the form关闭表单后datagridview值消失
【发布时间】:2016-03-06 04:10:12
【问题描述】:

我的数据网格有问题我使用此代码将选定的行从 datagrid1 复制到 datagrid2.. 我的数据网格连接到数据库中的表..

for (int i = 0; i < datagrid1.SelectedRows.Count; i++){
    int index = datagrid2.Rows.Add();
    datagrid2.Rows[index].Cells[0].Value = datagrid1.SelectedRows[i].Cells[0].Value.ToString();
    datagrid2.Rows[index].Cells[1].Value = datagrid1.SelectedRows[i].Cells[1].Value.ToString();
}

它工作正常并将所选值添加到 datagrid2.. 但问题是当我关闭表单并再次运行它时.. datagrid2 清除其所有值..

有什么方法可以将值保留在 datagrid2 中,并且只有在按下按钮时才将其清除?谢谢

【问题讨论】:

    标签: c# sql visual-studio datagridview


    【解决方案1】:

    有不同的方法来保存这些值,其中之一是:

    当你需要你的表单从屏幕上消失时,你不要关闭它,而只是像这样隐藏(假设它不是你的应用程序的主表单):

    // Using FormClosing event
    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
       // as example, exitingApp (bool) should be your global flag to distinguish 
       // if you want to hide this form only or you close your application completely
       if (!exitingApp) 
       {
         e.Cancel = true;
         Hide();
       }
    }
    

    考虑到您应该在某处保留对该表单的引用,以便能够再次显示它:

    if (form2 == null)
    {
       form2 = new Form2();
    } 
    form2.Show();
    

    另一种方法是在关闭表单之前将其内容存储在其他地方,并在再次加载表单时恢复,但我个人更喜欢第一种方式。

    【讨论】:

      【解决方案2】:

      您可以创建一个具有静态列表的静态类,并将gridview 的数据存储在其中。并在 page_load 上加载列表数据的 gridview。

      如下:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Data;
      using System.Web.UI.WebControls;
      /// <summary>
      /// Summary description for Global
      /// </summary>
      public static class Global
      {
      
          public static List<GridView> GridViewList = new List<GridView>();
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        • 2020-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多