我有gridview,它在加载时会从数据库中获取数据。我添加了用户通过DDl过滤此网格视图的选项我做了我的代码并且网格在加载时获取数据但是当我选择DDl时它没有获得任何数据我发现了断点,我注意到Gridview1.Databind()没有对grid进行任何操作。所以请任何人帮助我
protected void Page_Load(object sender, EventArgs e)
{
DataTable DT = new DataTable();
if (DDlCity.SelectedIndex<0)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("@DEALERAREA_ID", DDlCity.SelectedValue));
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
答案 0 :(得分:0)
在你的帖子中你可以把绑定代码放在条件
中if (!IsPostBack){
// Bind grid here looking for or used call to function something like BindGrid()
}
在BindGrid()函数中,您可以为网格视图编写绑定代码。
并在ddl选择索引更改事件后,您可以再次调用BindGrid()方法再次绑定。
还要检查您的下拉列表中是否有EnablePostBack - true。
答案 1 :(得分:0)
我想你对我说的话感到困惑......不用担心 这是一个给出示例代码的工作示例。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridFunction();
}
}
private void BindGridFunction()
{
try
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
if(DDlCity.SelectedIndex <0)
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
}
else
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("@DEALERAREA_ID", DDlCity.SelectedItem.Value));
}
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
catch(Exception ex)
{
DT = null; // etc...etc.. clear objects created
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridFunction();
}
我希望你得到我想说的话。您可以根据需要更改代码。
尚未测试但确定可行。
注意:我建议使用“DDlCity.SelectedItem.Value”而不是“DDlCity.SelectedValue”