Gridview数据源来自数据库存储过程

时间:2018-06-17 17:59:50

标签: c# sql-server winforms

这是数据库存储过程:

ALTER PROCEDURE [dbo].[getShift]
    @rfiddata VARCHAR(50)
AS
BEGIN
    SELECT 
        pd.TP, s.s_name, dt.dt_type, dr.dr_date
    FROM 
        TA_System_PersonalDetails pd
    INNER JOIN 
        TA_System_DutyRequest dr ON pd.TP = DR.TP
    INNER JOIN 
        TA_System_Duty d ON dr.d_ID = d.d_ID
    INNER JOIN 
        TA_System_Shift s ON d.s_ID = s.s_ID
    INNER JOIN 
        TA_System_DutyType dt ON d.dt_ID = dt.dt_ID
    WHERE 
        pd.rfid_card = @rfiddata
        AND dr.dr_date = CAST(GETDATE() AS DATE)
END

这是C#代码:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();

SqlCommand cmd = new SqlCommand("dbo.getShift", con);
cmd.Parameters.AddWithValue("@rfiddata", data);
cmd.CommandType = CommandType.StoredProcedure;

gvDetails.DataSource = cmd.ExecuteNonQuery();
con.Close();

gridview仍然无法显示该值。这个项目是用Windows形式的C#。因此,没有DataBind()功能。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我希望此代码能够提供帮助

首先,我们创建一个连接器来连接数据库

string cnStr = @"Persist Security Info=False;User ID=usr;password=pwe; Initial Catalog=theDataBase;Data Source=yourDatasource";

并创建SqlCommand,然后将CommandType设置为StoredProcedure

SqlCommand cmd = new SqlCommand();

然后创建一个SqlConnection并打开数据库:

using(SqlConnection con = new SqlConnection(cnStr))
{

   con.Open();

   cmd.Connection = con;
   cmd.CommandText = "dbo.getShift";    // this is the stored procedure to       execute
   cmd.CommandType = CommandType.StoredProcedure;

 }//Connection automatically closes here without the need to call conn.Close()

然后创建一个要填充的数据集作为gridview的数据源:

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

grdYourGrid.DataSource = ds;
grdYourGrid.DataBind();