Roger Luo

超越梦想一起飞
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# DataGridView 与 DataSet

Posted on 2013-03-26 19:20  Roger Luo  阅读(7775)  评论(0编辑  收藏  举报

以前得到DataSet的时候都是利用直接写sql语句(适合初学者)

public static DataSet GetDs(string sqlstr)
    {
        ds = new DataSet();
        sqlconn = new SqlConnection();
        sqlconn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["connstr"];
        sqlconn.Open();
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, sqlconn);
        da.Fill(ds);
        ConnClose();
        return ds;
    }

使用存储过程

SqlConnection sqlConn = new SqlConnection();
sqlConn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["connstr"];
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("GetAuthListByRole", sqlConn);
sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlDa.SelectCommand.Parameters.Add(new SqlParameter("@rolename", SqlDbType.VarChar, 50));
sqlDa.SelectCommand.Parameters[0].Value = roleName;
sqlDa.Fill(ds);
sqlConn.Close();
return ds;

DataTable获取存储过程的返回值

将定存储过程为如下:

CREATE PROCEDURE SP_TEST1
AS
SELECT * FROM TABLE_TEST;

调用改存储过程

SqlCommand cmd = new SqlCommand();
cmd.CommandText = “NameofStoreProcedure”;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.ExecuteNonQuery();

联系SqlDataAdapter与DataTable

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(yourdatatable);

接着修改DataGridView空间在绑定前

DataGridView dgv = new DataGridView();
dgv.Columns.Add(“EnglishName”, “ChineseName”);
dgv.Columns[“EnglishName”].DataProductName = “IDinDB”;
dgv.DataSource = dt;