在项目模板中选择所选值

时间:2011-09-22 20:30:59

标签: c# asp.net

我有一个名为BindItems()的方法,此方法将值传递给DataTable,然后将GridView绑定到它。

然后我在gridview中有一个包含下拉列表的itemtemplate,这个下拉列表从Gridview_RowDataBound下的代码后面的1-14填充,现在我需要想办法在另一个上获取DataTable中的Quantity值函数“BindItems()”和gridview中的每一行所以一个SelectedValue = datatable [“Quantity”]或者什么......我该怎么做?

protected void BinItems(int myId)
{
    //this data table contains a value "Quantity"
    DataTable dt = MyClass.getItems(myId);


    uxGrid.DataSource = dt;
    uxGrid.DataBind();
}

protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType.Equals(DataControlRowType.DataRow))
    {
        DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;

        if (Myddl != null)
        {
            for (int i = 1; i < 15; i++)
            {
                Myddl.Items.Add(i.ToString());
            }
        }
    }

//Some how i need to do a SelectedValue = datatable where field = Quantity for each row
}

2 个答案:

答案 0 :(得分:1)

您需要访问当前绑定行DataItem,在您的情况下,DataRowView(因为您绑定到DataTable):

protected void Gridview1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType.Equals(DataControlRowType.DataRow))
    {
        DropDownList Myddl = e.Row.FindControl("MyQuantity") as DropDownList;

        if (Myddl != null)
        {
            for (int i = 1; i < 15; i++)
            {
                Myddl.Items.Add(i.ToString());
            }
        }
    }

   //here goes the "magic"
   DataRowView dRow = e.Row.DataItem as DataRowView;
   if(dRow != null)
   {
       Myddl.SelectedValue = dRow["Quantity"].ToString();
   }
}

答案 1 :(得分:0)

您应该在DataTable dt之外,然后您将能够在函数

中访问它