如何将BUTTON值插入数据库

时间:2014-12-25 11:01:10

标签: c# mysql asp.net

您好我试图将按钮的值插入代码中:

以下是按钮的代码:

<asp:Button ID="addFriend" runat="server" ' CommandArgument ='<%# Eval("ProfileId") %>' 
     CommandName='<%# Eval("ProfileId") %>'  Value='<%# Eval("ProfileId") %>Text="Add Friend" 
     CssClass="btn btn-info" OnClick="addFriend_Click" />

以下是插入代码:

    protected void addFriend_Click(object sender, EventArgs e)
    {
        // Get the UserId of the just-added user
        MembershipUser currentUser = Membership.GetUser();
        Guid currentUserId = (Guid)currentUser.ProviderUserKey;
        var addFriend = sender as Button;
        var value = addFriend.Text;


        // Insert a new record into UserPro
        string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        string insertSql = "INSERT INTO User_Friend(ProfileId1, ProfileId) VALUES (@FriendProfileId, (SELECT ProfileId FROM User_Profile WHERE UserId = @UserId))";

        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
            myCommand.Parameters.AddWithValue("@FriendProfileId", addFriend.Text);
            myCommand.Parameters.AddWithValue("@UserId", currentUserId);

            myCommand.ExecuteNonQuery();
            myConnection.Close();
        }
    }

它可以工作,但它会插入按钮文本而不是值。

1 个答案:

答案 0 :(得分:2)

asp:Button类没有Value属性。

而是在表单中添加一个包含配置文件值的附加隐藏控件

<asp:HiddenField runat="server" ID="hdnFriend" Value='<%# Eval("ProfileId") %>' />

然后您可以在后面的按钮处理程序代码中使用它:

myCommand.Parameters.AddWithValue("@FriendProfileId", hdnFriend.Value);