尝试在rowDataBound期间向sqldatasource添加参数

时间:2010-08-11 19:45:05

标签: c# asp.net ado.net

所以我在gridview中有一个gridview(我有一对多的表)我的第一个gridview运行良好,但是我的第二个gridview有一个sqldatasource,它有一个select参数(默认值只是用于测试)

<asp:SqlDataSource ID="dsCountryByTripID" runat="server" 
        ConnectionString="<%$ ConnectionStrings:bahDatabase %>" 
        SelectCommand="spSelectCitiesByTripID" SelectCommandType="StoredProcedure">
        <SelectParameters>
        <asp:Parameter Type="Int32" Name="tripID"  DefaultValue="56" />
        </SelectParameters>
    </asp:SqlDataSource>

在我的Gridview1行数据绑定期间,我试图获取与tripID匹配的列。但是dsCountryByTripID是我的数据源,只能输入最后一个tripID。

 protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        GridView gv2 = (GridView)e.Row.FindControl("GridView2");
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            dsCountryByTripID.SelectParameters.Clear();
            DataRowView drv = (DataRowView)e.Row.DataItem;
            string tripID = (drv["pkiTripId"]).ToString();
            dsCountryByTripID.SelectParameters.Add("tripID", DbType.Int32, tripID);
            //gv2.DataBind();
            //e.Row.DataBind();

        }
    }

2 个答案:

答案 0 :(得分:1)

在这里你可以阅读为什么它只执行最后一次“tripId”:http://msdn.microsoft.com/en-us/library/tw738475(VS.80).aspx
sql数据源仅在页面末尾执行,因此每次遍历行时都会覆盖tripID。

您真的需要使用数据源吗?你不能使用ado.net或不同的数据访问吗?

希望这有帮助。

答案 1 :(得分:0)

首先,我们需要澄清您网页的结构。在我看来,dsCountryByTripID是在Gridview1之外声明的,而不是在Gridview1中声明的。这可能就是为什么你的dsCountryByTripID只会输入最后一个tripID。

为了做你想做的事,结构应该是这样的:

<asp:gridview id="gv1" runat="server" DataSourceID="ds1">
...
    <asp:gridview id="gv2nested" runat="server" DataSourceID="dsCountryByTripID">
    </asp:gridview>
    <asp:SqlDataSource ID="dsCountryByTripID" runat="server" 
    ConnectionString="<%$ ConnectionStrings:bahDatabase %>" 
    SelectCommand="spSelectCitiesByTripID" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:Parameter Type="Int32" Name="tripID"  DefaultValue="56" />
        </SelectParameters>
    </asp:SqlDataSource>
...
</asp:gridview>
<asp:SqlDataSource ID="ds1" runat="server" >
</asp:SqlDataSource>

接下来,要将正确的值分配给内部数据源选择参数,可以在外部gridview(gv1)RowCreated事件处理程序中执行此操作。

protected void gv1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //Retrieve the inner gridview
        //Retrieve the inner sqldatasource
        //Retrieve and assign selectparameter value
    }

它类似于您发布的C#代码,但在将值分配给selectparameter之前,您还需要使用FindControl来检索现在的嵌套 sqldatasource(dsCountryByTripID)。 (试着教一个人在这里钓鱼,但是如果你需要更多的帮助或者上面的情况不是你的情况,请告诉我:)