我正在尝试使用asp:checkbox
将选定的行存储到CourseParticipants
表中,但是没有将选定的记录存储到数据库中。没有显示错误,但刷新到同一页面并显示已检查的记录。我正在尝试选择用户。
先感谢您!
以下是标记:
<table class="table table-hover">
<thead style="background-color: #92d36e">
<tr>
<td><b>Employee Name</b></td>
<td><b>Position</b></td>
<td><b>Actions</b></td>
</tr>
</thead>
<tbody>
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td><asp:CheckBox ID="cbEmployee" runat="server" />
</a></td>
</tr>
</ItemTemplate>
</asp:ListView>
</tbody>
</table>
<asp:Button ID="btnAddParticipants" runat="server"
class="btn btn-success" OnClick="btnAddParticipants_Click"
Text="Add Participants" />
这是C#
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = @"SELECT EmployeeID, FirstName, LastName, Position FROM Employees";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmployee");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = @"INSERT INTO CourseParticipants VALUES (@TrainingModuleID, @EmployeeID, @Active, @DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("@EmployeeID", idValue);
cmd.Parameters.AddWithValue("@Active", 1);
cmd.Parameters.AddWithValue("@DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
答案 0 :(得分:0)
如果始终要插入DateTime.Now
,则可以使用getdate()
函数:
string query = @"INSERT INTO CourseParticipants VALUES (@TrainingModuleID, @EmployeeID, @Active, getdate())";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("@EmployeeID", idValue);
cmd.Parameters.AddWithValue("@Active", 1);
cmd.ExecuteNonQuery();
}
但这是特定于数据库的,那么您正在使用什么数据库? https://docs.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql?view=sql-server-2017
我还将根据您的数据库方案将txtCourseID.Text
转换/转换为整数(32或64)。只是为了确保它是一个OK值...而不是字符串(nvarchar)。
我还删除了连接的关闭部分,因为它位于using块中。