2013-03-18 88 views
0

我正在做一个孟买本地火车计时项目作为我的课程项目..我怎么能附加我的数据源从数据库内的GridView?如何从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

您需要使用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(); 
      } 
     } 

    } 
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

问候