更新数据库中的单元格但不删除以前的值

时间:2016-05-21 20:05:43

标签: c# asp.net sql-server

我正在asp.net和C#实施健美健身房网站。 我想邀请健身会员参加像瑜伽,ABS。 我想将它们添加到表Workout和名为Participants的列中。 该表有6列(ID,日期,类型,描述,状态,参与者)。 这是我的代码。

GridViewRow row = DataGrid1.SelectedRow;
string hour = row.Cells[1].Text;
string type = row.Cells[2].Text;
string participant = Session["New"].ToString() + ", ";

SqlConnection EnrolForConn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginConnectionString"].ConnectionString);
EnrolForConn.Open();
string EnrolForStatement = "update [Workout] set [Participants]=@Participants where Date = '" + hour + "' and Type = '" + type + "'";
SqlCommand EnrolForCommand = new SqlCommand(EnrolForStatement, EnrolForConn);
EnrolForCommand.Parameters.AddWithValue("@Participants", participant);

int x = EnrolForCommand.ExecuteNonQuery();
if (x == 0)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "alert('Error !!!');", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "alert('You have been enrolled for class !!!');", true);
}

EnrolForConn.Close();

当我添加第一个参与者时,它有效。但是当我添加第二个(登录到另一个帐户)时,它会删除第一个帐户。我不想删除以前的参与者。

另外,我想限制参加人数,例如最多10个(我使用逗号分隔参与者)。

有什么建议吗? ;) 在此先感谢!!!

1 个答案:

答案 0 :(得分:4)

您实际上正在使用参与者中存在的值更新Participants列,因此只会保留最后一列。

为了让所有参与者都参与该领域,你必须写下如下内容:

// get all the participants in a list
// e.g. IList<String> participantsList
participant = String.Join(", ", participantsList);

旁注:

但是,建议对数据进行规范化,并为参与者提供单独的表格。这样,您就可以为用户/参与者定义一个表,并且只在Event和Participant之间存储X关系。

不仅保存了存储空间,而且以后处理事件和参与者的查询也更容易编写(没有字符串拆分)。

此外,尝试将参数用于可以参数化的所有内容:

string EnrolForStatement = "update [Workout] set [Participants]=@Participants where Date = @Hour and Type = @Type";
EnrolForCommand.Parameters.AddWithValue("@Hour", hour);
EnrolForCommand.Parameters.AddWithValue("@Type", type);
相关问题