在页脚模板中填充DropDownList c#

时间:2014-08-28 14:40:33

标签: c# asp.net gridview

我需要在 GridView 页脚模板填充一个 DropDownList

教程是:

http://technico.qnownow.com/how-to-populate-dropdownlist-based-on-another-dropdownlist-inside-a-gridview/

我尝试使用此解决方案但没有成功,因为错误是:

Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.

代码隐藏的这一行中:

area.SelectedValue = drv["area"].ToString();

我非常感谢您在解决这个问题时能给我的任何帮助。

这是我的代码:

    if (e.Row.RowType == DataControlRowType.Footer)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;

        DropDownList area = (DropDownList)e.Row.FindControl("area");
        area.DataTextField = "area";
        area.DataValueField = "area";
        area.DataSource = RetrieveCategories();
        area.DataBind();
        area.SelectedValue = drv["area"].ToString();
    }


private DataTable RetrieveCategories()
{
    sql = " SELECT DISTINCT area FROM doTable; ";

    DataTable dtCategories = new DataTable();

    using (OdbcConnection myConnectionString =
       new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        myConnectionString.Open();
        using (OdbcCommand cmd = new OdbcCommand(sql, myConnectionString))
        {
            OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
            adapter.Fill(dtCategories);
        }
    }
    return dtCategories;
}

1 个答案:

答案 0 :(得分:0)

问题是你的drv对象没有任何数据(null),因为它在页脚中。绑定网格并将所有数据链接到网格行,无论数据行数是多少,页脚都没有任何内容。

如果您需要其中一行中的数据,我建议创建一个全局变量,并在绑定行数据时分配它。然后,一旦您的页脚绑定发生,该值将在您指定的全局变量中可用。

例如:

// Create global *NOT* in your binding method
private string _area = "";


// Then in your binding method change it to read the row data assuming this is
// where you want to get the area from.
if (e.Row.RowType == DataControlRowType.DataRow)
{
    DataRowView drv = e.Row.DataItem as DataRowView;
    area = drv["area"].ToString();
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
    // your other code here...
    // then replace the assignment
    area.SelectedValue = _area;
}