这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
connection db_obj1 = new connection();
SqlConnection sql_obj = db_obj1.Connect();
if (this.DropDownList1.SelectedIndex >= 0)
{
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
// SqlDataReader query_read = query.ExecuteReader();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("@tab",);
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
}
}
问题在于,当我运行代码时,即使选择了不同的选项,我也只看到下拉列表而没有GridView。我试过调试,似乎表格已经填满了,我认为唯一的问题是在'grd.FindControl(“GridView1”)行中。这是给gridview提供数据源的正确方法吗?
答案 0 :(得分:0)
根据我的意思,你不应该使用
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
代表尝试如下
string brand = DropDownList1.SelectedItem.Text;
之后发出一个查询。 我希望它会让人感到沮丧。
编辑后现在使用此代码
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("@tab",);
DataSet ds = new DataSet();
DataTable table;
adapter.SelectCommand = command;
adapter.Fill(ds, "ABC");
table = ds.Tables["ABC"];
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
<强>解释强>
adapter.Fill(ds, "ABC");
这里ABC是表格的临时名称,你可以拿走任何东西。
table = ds.Tables["ABC"];
并在此处写入与临时表名称相同的表名。 现在尝试一下。