(C#ASP站点)现在我有一个预先检查的CheckBoxList,具体取决于用户在表单中选择的内容。这是编写预检以供参考的代码。它完美地运作。每当由用户选择引起新的预检查时=>回发
DataTable DefaultActivity = GetData();
// Resets checkboxes to blank in between postbacks
for (int p = 0; p < CheckBoxList1.Items.Count; p++)
{
CheckBoxList1.Items[p].Selected = false;
}
// Fills in the prechecked boxes
if (DefaultActivity.Rows.Count > 0)
{
int SelectedRoleID = Int32.Parse(RadioButtonList2.SelectedValue);
for (int i = 0; i < DefaultActivity.Rows.Count; i++)
{
int DatabaseRoleID = Convert.ToInt32(DefaultActivity.Rows[i]["roleid"]);
if (SelectedRoleID == DatabaseRoleID)
{
int DatabaseActivityID = Convert.ToInt32(DefaultActivity.Rows[i]["activityid"]);
for (int j = 0; j < CheckBoxList1.Items.Count; j++)
{
if (DatabaseActivityID == Convert.ToInt32(CheckBoxList1.Items[j].Value))
{
CheckBoxList1.Items[j].Selected = true;
}
}
}
}
}
我遇到的问题是,除了预先检查的框之外,用户应该能够检查更多的框,但是当他们单击“提交”按钮时,它不会检测新选中的框。这是提交按钮代码。
// Data into the request table
SqlConnection sqlConn = new SqlConnection("Server=x;Database=x;User=x;Password=x;Trusted_Connection=False;");
string Statement = "INSERT INTO table (x) OUTPUT INSERTED.requestid VALUES (x)";
SqlCommand sqlComm = new SqlCommand(Statement, sqlConn);
// Grabs the auto-created RequestID to forward to the next page
sqlComm.Connection.Open();
string RequestID = Convert.ToString((Int32)sqlComm.ExecuteScalar());
sqlComm.Connection.Close();
sqlComm.Connection.Dispose();
// Data into the x table
SqlConnection ActivitysqlConn = new SqlConnection("Server=x;Database=x;User=x;Password=x;Trusted_Connection=False;");
string ActivityStatement = "INSERT INTO table (x) VALUES (x)";
for (int k = 0; k < CheckBoxList1.Items.Count; k++)
{
if (CheckBoxList1.Items[k].Selected == true)
{
SqlCommand ActivitysqlComm = new SqlCommand(ActivityStatement, ActivitysqlConn);
ActivitysqlComm.Connection.Open();
ActivitysqlComm.ExecuteNonQuery();
ActivitysqlComm.Connection.Close();
}
}
Response.Redirect("nextscreen.aspx?RequestID=" + RequestID);
任何想法为什么提交按钮都看不到新的支票?它读取预检很好。边题 - 是否有更有效的方式来打开/关闭连接?很好,我是新人:)
答案 0 :(得分:1)
要回答您的SQL问题,这是“干净”的方式:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "mysp_GetValue";
command.CommandType = CommandType.StoredProcedure;
connection.Open();
object ret = command.ExecuteScalar();
}
您应该将连接字符串存储在某个位置的配置中,并在可行的情况下使用存储过程来帮助缓解SQL注入漏洞。
在您回答评论后,我们可以解决您的检查状态更改失败。
答案 1 :(得分:1)
轻松修复 - 我将预检代码从PageLoad移动到RadioButtonList,这是影响预检查的对象。现在可以正确保存所有预检和附加检查。