在gridview中绑定HiddenField

时间:2013-11-25 19:32:53

标签: c# asp.net gridview hidden-field

我想绑定Hidden Field,因为我想将代码后面的值传递给asp:Parameter Name="HOME_TEAM_COACH_ID" Type="Int32"

我的asp:

<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdating" >
    <EditItemTemplate>           
        HOME_TEAM:
        <asp:DropDownList ID="DropDownListHometeam" runat="server"
            DataSourceID="SqlDataGetTeams"
            DataTextField="NAME" DataValueField="ID" SelectedValue='<%# Bind("HOME_TEAM_ID") %>'>
        </asp:DropDownList>  
        <asp:HiddenField runat="server" ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>' /> 
    </EditItemTemplate>

c#背后是:

protected void FormView1_ItemUpdating(object sender, FormViewUpdatedEventArgs e)
{
    if (FormView1.CurrentMode == FormViewMode.Edit)
    {
        DropDownList HomeTeamId = FormView1.FindControl("DropDownListHometeam") as DropDownList;            
        string team = string.Format("{0}", HomeTeamId.Text);
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BasketballConnectionString1"].ToString());
        conn.Open();
        string queryHome = "SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")";
        SqlCommand cmd = new SqlCommand(queryHome, conn); 


        var Home_Coach_Id = cmd.ExecuteScalar().ToString();
        HiddenField HomeCoachIdLabel = FormView1.FindControl("testLabel") as HiddenField;
        HomeCoachIdLabel.Value = Convert.ToString(Home_Coach_Id);
        conn.Close();

我希望在最后四行的帮助中传递Home_Coach_Id值以绑定asp:HiddenField ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>'

单击更新时,它不会更改数据库中的值。 (当我调试时,在最后一行中它给了我正确的HomeCoachIdLabel.Value。) 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您不需要显式设置HiddenField的{​​{1}}属性,因为它是由您的标记中的Value完成的。

我相信您的问题是您没有在<%# Bind("HOME_TEAM_COACH_ID") %>声明中将HOME_TEAM_COACH_ID从查询返回到数据库:

SELECT

答案 1 :(得分:0)

问题是它需要预渲染方法而不是onitemupdated方法。

   asp:FormView ID="FormView1" runat="server" OnPreRender="FormView1_OnPreRender" >

以及c#

    protected void FormView1_OnPreRender(object sender, FormViewUpdatedEventArgs e)

{

当我将它放在页面加载{}中时它也有效。 下一步是进行插入事件....