【问题标题】:Populate DropDownList in Footer Template c#在页脚模板 c# 中填充 DropDownList
【发布时间】:2014-08-28 22:52:58
【问题描述】:

我需要在 GridViewFooter Template填充一个 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;
}

【问题讨论】:

  • 页眉和页脚行没有数据项,因此drv 在您的代码中为空。
  • 对不起,我听不懂,我需要更换教程吗?
  • 您已经更改了它。适用于 GridView 中 DataRow 类型行的内容可能不适用于页脚。这正是您的情况 - 教程适用于 DataRow(DataItem 有意义且不为空),而您正在尝试使用 Footer

标签: c# asp.net gridview


【解决方案1】:

问题是您的drv 对象没有任何数据(空),因为它在页脚中。网格已绑定,所有数据都链接到网格行,无论数据行数如何,页脚都没有任何内容。

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

例如:

// 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;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2020-09-04
    相关资源
    最近更新 更多