我正在使用 asp.net 和 C# 实现 Bodybuilding Gym 网站。 我想招收健身房成员(member)参加类(class),例如 Yaga ,腹肌。 我想将它们添加到表 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 个(我使用逗号分隔参与者)。
有什么建议吗? ;) 提前致谢!!!
最佳答案
您实际上是在用参与者中存在的值更新 Participants
列,因此只会保留最后一个。
为了让该领域的所有参与者都参与进来,您必须编写如下内容:
// get all the participants in a list
// e.g. IList<String> participantsList
participant = String.Join(", ", participantsList);
旁注:
但是,建议对您的数据进行规范化处理,并为参与者准备一个单独的表格。这样,您可以为用户/参与者定义一个表,并且只存储事件和参与者之间的 X 关系。
不仅节省了存储空间,而且将来处理事件和参与者的查询也将更容易编写(无字符串拆分)。
此外,尝试对所有可以参数化的东西使用参数:
string EnrolForStatement = "update [Workout] set [Participants]=@Participants where Date = @Hour and Type = @Type";
EnrolForCommand.Parameters.AddWithValue("@Hour", hour);
EnrolForCommand.Parameters.AddWithValue("@Type", type);
关于c# - 更新数据库中的单元格但不删除以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37367473/