如何将按钮值插入数据库
本文关键字:插入 数据库 按钮 | 更新日期: 2023-09-27 18:35:13
嗨,我正在尝试将按钮的值插入代码中:
这是按钮的代码:
<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();
}
}
它有效,但它插入按钮文本而不是值。
asp:Button 类没有 Value
属性。
而是在窗体中添加一个包含配置文件值的附加隐藏控件
<asp:HiddenField runat="server" ID="hdnFriend" Value='<%# Eval("ProfileId") %>' />
然后,您可以在按钮处理程序代码隐藏中使用它:
myCommand.Parameters.AddWithValue("@FriendProfileId", hdnFriend.Value);