如果我们有2个查询,如何在Gridview中显示数据

时间:2013-10-29 12:05:54

标签: asp.net

我有两个查询,对于那两个查询我已经两个网格视图

select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided    where start_date>=Getdate() and branch_code='Ameerpet'

select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Hi-Tech City'

在我的页面加载期间,我需要在网格视图中显示数据。

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local); Initial Catalog=gateway; User   Id=sa; Password=wilshire@rnd; Integrated Security=false";


            //Assigning Query
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";

cmd.CommandText = "select course_name , start_date, end_date, timings, fee, branch_code  from coursesprovided where start_date>=Getdate() and branch_code='Ameerpet'";

            cmd.CommandType = CommandType.Text;


            //Execute the COmmand
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            gvap.DataSource = ds;
            gvap.DataBind();
}

有没有其他选择,而不是 2个SQL命令,2个SqlDataAdapter,2个数据集 .....

1 个答案:

答案 0 :(得分:0)

你能不能将这两个问题合并为一个?

 SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] ='Ameerpet' OR [branch_code] = 'Hi-Tech City')

请记住,如果可能的话,应该避免硬编码字段值,而是使用参数。

 String branchCode1 = "Ameerpet";
 String branchCode2 = "H-Tech City";

 cmd.CommandText = "SELECT [course_name], [start_date], [end_date], [timings], [fee], [branch_code] FROM [coursesprovided] WHERE [start_date] > = GETDATE() AND ([branch_code] = @BranchCode1 OR [branch_code] = @BranchCode2)";

 da.SelectCommand.Parameters.AddWithValue("BranchCode1", branchCode1);
 da.SelectCommand.Parameters.AddWithValue("BranchCode2", branchCode2);

这段代码被简化了......你可以以你想要的任何方式传递参数值,你应该通过将整个事物定义为单独的函数或存储过程来保持清洁,这样你就可以通过无论你想要什么价值。我刚刚在代码中定义了两个参数用于说明目的。