在GridView的代码中更改Container DataItem

时间:2012-09-24 15:11:54

标签: c# asp.net gridview

我想知道我是否可以在gridview中更改代码隐藏中的Container.DataItem。我的意思是,如果我想根据条件将Dataitem从“SellingPaymentMethod”更改为“DeliveryPaymentmethod”。

我使用相同的存储过程来获取销售和交付的信息。因此,如果它是销售它应该是SellingPaymentmethod,否则它应该是DeliveryPaymentmethod。这是在使用C#的ASP.Net中。

<asp:TemplateField ItemStyle-Width="70" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
      <asp:Label ID="lblSellingPaymentMethod" runat="server"
         Text='<%#DataBinder.Eval(Container.DataItem,"SellingPaymentMethod") %>'>
      </asp:Label>
    </ItemTemplate>
 </asp:TemplateField>



if(Condition1 = "Selling")
{
    use sellingpaymentmethod container
}
else
{
    use deliverypaymentmethod
}

编辑:

if (e.Row.RowType != DataControlRowType.DataRow)
    {
        return;
    }

    foreach (DataRow dtrCurrentRow in (((System.Data.DataView)grdDetail.DataSource)).Table.Rows) 
    {
        //DataRow row = (DataRow)e.Row.DataItem;
        Label lblPaymentMethod = e.Row.FindControl("lblPaymentMethod") as Label;
        Label lblBalance = e.Row.FindControl("lblTotalSold") as Label;
        Label lblBalanceCollected = e.Row.FindControl("lblTotalCollected") as Label;

        if (lblTypeofDay.Text == "Selling")
        {
            lblPaymentMethod.Text = dtrCurrentRow["SellingPaymentMethod"].ToString();
        }
        else if (lblTypeofDay.Text == "Delivery")
        {
            lblPaymentMethod.Text = dtrCurrentRow["DeliveryPaymentmethod"].ToString();
        }
     }

这就是我使用你的代码的方式。我不确定为什么所有行都在paymentmethod列中具有最后一行值。

我在btnSubmit_OnClick函数中有数据绑定代码

DataView myDataView = new DataView();
myDataView = dsnew.Tables[0].DefaultView;
grdDetail.DataSource = myDataView;
grdDetail.DataBind();

1 个答案:

答案 0 :(得分:1)

创建一个RowDataBound事件处理程序并在那里进行更改。

.aspx的:

<asp:GridView id="gridView1" runat="server" 
    OnRowDataBound="gridView1_RowDataBound" />

代码背后:

public void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType != DataControlRowType.DataRow)
    {
        return;
    }

    DataRow row = (DataRow)e.Row.DataItem;

    Label lblSellingPaymentMethod = 
        e.Row.FindControl("lblSellingPaymentMethod") as Label;

    if(condition == true)
    {
        lblSellingPaymentMethod.Text = row["sellingpaymentmethod"].ToString();
    }
    else
    {
        lblSellingPaymentMethod.Text = row["deliverypaymentmethod"].ToString();
    }
}