0

我正在将孟买当地的火车时刻表项目作为我的课程项目。我如何将我的数据源从数据库中附加到 gridview 中?

SqlCommand cmd;

protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
    con.Open();

    cmd = new SqlCommand("Select * from @d where(Select * from @c where Source = @a AND Destination = @b)",con);
    cmd.Parameters.AddWithValue("@d", DropDownList3.SelectedValue);
    cmd.Parameters.AddWithValue("@c",DropDownList3.SelectedValue);
    cmd.Parameters.AddWithValue("@a",DropDownList1.SelectedValue);
    cmd.Parameters.AddWithValue("@b",DropDownList2.SelectedValue);





    //int i = cmd.ExecuteNonQuery();

    //if (i > 0)
    //{
    GridView1.DataSource = //what shud i put here in as a datasource??
    GridView1.DataBind();
    //}
}
4

2 回答 2

1

Just simply do some thing like this:

con.Open(); 
SqlCommand cmd = new SqlCommand("Select * from @d where(Select * from @c where Source = @a AND Destination = @b)",con);
cmd.Parameters.AddWithValue("@d", DropDownList3.SelectedValue);
cmd.Parameters.AddWithValue("@c",DropDownList3.SelectedValue);
cmd.Parameters.AddWithValue("@a",DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("@b",DropDownList2.SelectedValue);

SqlDataAdapter adapt = new SqlDataAdapter();
DataTable dt = new DataTable();
adapt.SelectCommand = cmd;
adapt.Fill(dt);
GridView GridView1 = new  GridView();
GridView1.DataSource = dt;
GridView1.DataBind();

Then this link might be helpful to you : The C# Station ADO.NET Tutorial

Best Regards

于 2013-03-18T08:51:16.253 回答
0

您需要使用SQlDataReaderSqlDataadpter/Dataset

   using(SqlConnection con = new SqlConnection(connstring))
    {
        con.Open(); 
      using(SqlCommand cmd = new SqlCommand("yourQuery",con))
       {
           cmd = new SqlCommand("Select * from @d where(Select * from @c where Source = @a AND Destination = @b)",con);
           cmd.Parameters.AddWithValue("@d", DropDownList3.SelectedValue);
          cmd.Parameters.AddWithValue("@c",DropDownList3.SelectedValue);
          cmd.Parameters.AddWithValue("@a",DropDownList1.SelectedValue);
          cmd.Parameters.AddWithValue("@b",DropDownList2.SelectedValue);

          using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
            {
              Dataset dstList= new Dataset ();
              adapter.Fill(dstList);
              GridView1.DataSource = dstList;
             GridView1.DataBind();
            }
       }

    }
于 2013-03-18T08:31:52.870 回答