我正在制作一个孟买当地的火车时刻项目作为我的班级项目..我如何在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();
//}
}
答案 0 :(得分:1)
只需做一些这样的事情:
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();
然后,此链接可能对您有所帮助:The C# Station ADO.NET Tutorial
最好的问候
答案 1 :(得分:0)
您需要使用SQlDataReader
或SqlDataadpter/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();
}
}
}