【问题标题】:Binding empty controls to gridview and retrieving their values将空控件绑定到 gridview 并检索它们的值
【发布时间】:2012-06-20 07:53:23
【问题描述】:

我使用列表绑定了一个gridview

private void BindEntirePropertyGrid()
{
    List<Tbl_RoomMaster> items = new List<Tbl_RoomMaster>();
    for (int i = 0; i < Convert.ToInt32(bedrooms.Text); i++)
    {
        items.Add(objRoomMaster);
    }
    ViewState["GridView1"] = items;
    GridView1.DataSource = items;
    GridView1.DataBind();

}

现在我尝试检索值,但显示错误

if (ViewState["GridView1"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["GridView1"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    Label box1 = (Label)GridView1.Rows[rowIndex].Cells[1].FindControl("lblbedroom");
                    DropDownList box2 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("ddpAccomodates");
                    DropDownList box3 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("ddpBathroom");
                    DropDownList box4 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("ddpBedType");
                    //get the values from the TextBoxes
                    //then add it to the collections with a comma "," as the delimited values
                    sc.Add("BedRoom" + box1.Text + "," + box2.SelectedItem.Value + "," + box3.SelectedItem.Value + "," + box4.SelectedItem.Value);
                    rowIndex++;
                }
                //Call the method for executing inserts
                InsertRoomDetails(sc, propIDreturnedOnSave);
            }
        }

还有其他方法可以将空控件绑定到 gridview 并检索值吗?

错误 在这一行:

DataTable dtCurrentTable = (DataTable)ViewState["GridView1"];

Unable to cast object of type 'System.Collections.Generic.List`1[CT.Bussiness.Tbl_RoomMaster]' to type 'System.Data.DataTable'.

【问题讨论】:

  • 错误内容是什么
  • 您遇到的错误是什么?顺便说一句,ViewState["GridView1"] 的内容不是DataTable
  • 您在哪个事件中尝试获取类似的值?
  • **错误**无法将“System.Collections.Generic.List`1[CT.Bussiness.Tbl_RoomMaster]”类型的对象转换为“System.Data.DataTable”类型。跨度>

标签: c# gridview


【解决方案1】:

ViewState["GridView1"] 的内容不是 DataTable。

改变

DataTable dtCurrentTable = (DataTable)ViewState["GridView1"];

List<Tbl_RoomMaster> dtCurrentTable = (List<Tbl_RoomMaster>)ViewState["GridView1"];

你也必须改变

if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)

if (dtCurrentTable.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Count; i++)

【讨论】:

  • 现在错误移到下一行“System.Collections.Generic.List”不包含“行”的定义
  • 查看我的编辑。您必须更改引用 dtCurrentTable 的其他内容,因为它不再是 DataTable
  • tat 工作 riki...非常感谢,感谢 STACK Guys 提供这个精彩的网站..
  • 很高兴能帮上忙 :) 如果您能接受这个作为正确答案,那就太好了。
猜你喜欢
  • 2011-10-12
  • 2010-10-30
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多