【问题标题】:How to show data using datagrid with C# + SQL Server如何使用带有 C# + SQL Server 的数据网格显示数据
【发布时间】:2012-04-22 14:34:59
【问题描述】:

我想询问更多使用数据网格将数据从 SQL Server 显示到 WinForm。 我一直在创建一个数据网格,显示数据的存储过程是

ALTER PROC [dbo].[SP_GetData]
AS
  SELECT nama , nim
  FROM tabledata

我已经在 C# 中创建了访问数据库和存储过程的函数

string Sp_Name = "dbo.SP_GetData";

SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=.");
SqlCon.Open();

SqlCommand SqlCom = new SqlCommand(Sp_Name , SqlCon);
SqlCom.CommandType = CommandType.StoredProcedure;

List<mahasiswaData> listMahasiswa = new List<mahasiswaData>();

using (SqlDataReader sqlDataReader = SqlCom.ExecuteReader())
{
   if (sqlDataReader.HasRows)
   {
      while (sqlDataReader.Read())
      {
         mahasiswaData DataMhs = new mahasiswaData();
         DataMhs.Nama = sqlDataReader["Name"].ToString();
         DataMhs.Umur = Convert.ToInt32(sqlDataReader["Age"]);
         listMahasiswa.Add(DataMhs);
      }
   }
}

SqlCon.Close();
return listMahasiswa;

最后,在显示按钮中我添加了这段代码

dgvmahasiswa.DataSource = new MahasiswaDB().LoadMahasiswa();

有人能告诉我问题出在哪里或替代方案吗?

非常感谢! :D

【问题讨论】:

  • 它到底有什么问题?除了建议进行一些重构,不在 catch 块中返回 null (你至少应该记录错误,这样你就知道事情是否出错了),以及更多地使用 using 关键字,这看起来很有效。另请注意,如果您的查询运行但未返回任何行,您将只返回一个空列表Mahasiswa
  • 非常感谢您的评论 :) :) 我添加了 try-catch 以防出现一些错误。但是,我最后总是收到错误的返回。仅供参考,我已经添加了一些数据到数据库中的表..

标签: c# sql-server sql-server-2008 datagrid


【解决方案1】:

需要考虑的一些事情:

  1. 目前,如果您的代码遇到异常,您将留下一个 SqlConnection 闲逛;您已经使用了 using 模式 SqlDataReader;你应该把它扩展到你所有的一次性用品 对象。

  2. 您正在吞咽异常;如果您的查询失败,则连接 无法制作,或者发生了其他事情,你永远不会真正知道 - 你的函数只会返回 null。

  3. 姓名或年龄是否可以为空?年龄不是数字? 没有任何意外值的测试,你也永远不会 了解一下。

  4. 如果您没有任何记录,您将返回一个空列表。这是 想要?还是您想知道没有记录?

你可能更喜欢看这样的东西:

public List<mahasiswaData> GetData(){


    List<mahasiswaData> gridData = new List<mahasiswaData>();


    try{

        using(SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=."))
        {
            using(SqlCommand command = new SqlCommand())
            {
                command.Connection = conn;
                command.CommandType = CommandType.StoredProcedure;
                command.Text = "dbo.SP_GetData";

                using(SqlDataReader reader = command.ExecuteReader())
                {
                    if(reader.HasRows){
                        while(reader.Read())
                        {
                           object rawName = reader.GetValue(reader.GetOrdinal("Name"));
                           object rawAge = reader.GetValue(reader.GetOrdinal("Age"));

                           if(rawName == DBNull.Value || rawAge == DBNull.Value)
                           {
                               //Use logging to indicate name or age is null and continue onto the next record
                               continue;
                           }
                           //Use the object intializer syntax to create a mahasiswaData object inline for simplicity
                           gridData.Add(new mahasiswaData()
                                                   {
                                Nama = Convert.ToString(rawName),
                                                        Umur = Convert.ToInt32(rawAge) 
                                                   });


                        }
                    }
                    else{
                        //Use logging or similar to record that there are no rows. You may also want to raise an exception if this is important.
                    }

                }

            }


        }


    }
    catch(Exception e)
    {
       //Use your favourite logging implementation here to record the error. Many projects use log4Net
       throw; //Throw the error - display and explain to the end user or caller that something has gone wrong!
    }


    return gridData;


}

请注意,如果您确定年龄或姓名永远不会为空,那么您可以简化中间部分:

while (reader.Read())
{
    //Use the object intializer syntax to create a mahasiswaData object inline for simplicity
    gridData.Add(new mahasiswaData()
    {
        Nama = reader.GetString(reader.GetOrdinal("Name")),
        Umur = reader.GetInt32(reader.GetOrdinal("Age"))
    });

}

【讨论】:

  • 非常感谢 :D :D 我想试试你的代码,但让我学习一下你的代码.. :) 我能再问一些吗,我没有编辑数据网格属性中的所有内容..只是在它们后面添加一些代码..有什么问题吗?
  • 不应该有@pegasustech。它应该可以工作,但它可能看起来不如所有必要的属性集那样好。值得先获取数据,然后玩弄网格的呈现。
  • 非常感谢@dash 看来你是最近回答我问题的人 :D :D 问题现在解决了,主要问题是我指向我的 sql 服务器上的另一个数据库.. 非常感谢:)
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 2021-12-07
  • 2011-03-24
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
相关资源
最近更新 更多