我有一个显示帖子的数据列表,我添加了文本框和添加评论的按钮,但是当我测试网站并添加评论时,我发现评论是为帖子正确添加的,但其余的添加了空白评论的帖子......?
任何人都知道如何处理这个问题?这是我的代码:
protected void Button9_Click1(object sender, EventArgs e)
{
foreach (DataListItem item in DataList2.Items)
{
TextBox TextBox1 = (TextBox)item.FindControl("TextBox1");
string text = TextBox1.Text;
Label post_IDLabel = (Label)item.FindControl("post_IDLabel");
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("comment", conn);
cmd.CommandType = CommandType.StoredProcedure;
int post_ID = Convert.ToInt32(post_IDLabel.Text);
string comment = text;
string email = Session["email"].ToString();
int course_ID = Convert.ToInt32(Request.QueryString["courseID"]);
cmd.Parameters.Add(new SqlParameter("@course_ID", course_ID));
cmd.Parameters.Add(new SqlParameter("@comment", comment));
cmd.Parameters.Add(new SqlParameter("@myemail", email));
cmd.Parameters.Add(new SqlParameter("@postID", post_ID));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
这是评论程序
CREATE PROC comment
@comment VARCHAR (100),
@myemail VARCHAR (30),
@postID INT,
@course_ID INT
AS
IF @myemail IN (SELECT student_email FROM Students_Subscribes_Course_pages WHERE subscribed = 1)
OR @myemail IN (SELECT added_email FROM Lecturers_Adds_Academics_Course_page WHERE course_ID = @course_ID)
AND @postID IN (SELECT post_ID FROM Posts WHERE @postID = @postID) OR @myemail =
(SELECT page_creator FROM Course_pages WHERE course_ID = @course_ID) AND @postID IN
(SELECT post_ID FROM Posts)
INSERT INTO Members_Comments_Posts (commenter,post_ID, comment_content)
VALUES (@myemail, @postID, @comment)
ELSE
PRINT 'sorry, you are not subscribed or post not found'
答案 0 :(得分:2)
问题在于您为列表中的每个项目执行相同的代码,而不是为那些项目留下评论的项目或当前所选项目。
对此的一个解决方案是在执行数据库代码之前查看是否设置了文本。
以下是我将如何重写循环:
foreach (DataListItem item in DataList2.Items)
{
TextBox TextBox1 = (TextBox)item.FindControl("TextBox1");
string text = TextBox1.Text;
if (!string.IsNullOrEmpty(text)) {
Label post_IDLabel = (Label)item.FindControl("post_IDLabel");
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("comment", conn);
cmd.CommandType = CommandType.StoredProcedure;
int post_ID = Convert.ToInt32(post_IDLabel.Text);
string comment = text;
string email = Session["email"].ToString();
int course_ID = Convert.ToInt32(Request.QueryString["courseID"]);
cmd.Parameters.Add(new SqlParameter("@course_ID", course_ID));
cmd.Parameters.Add(new SqlParameter("@comment", comment));
cmd.Parameters.Add(new SqlParameter("@myemail", email));
cmd.Parameters.Add(new SqlParameter("@postID", post_ID));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
这将确保对任何帖子的任何评论都会更新,但您可能需要更新逻辑以确保只更新所选帖子。
此外,您应该打开/关闭连接并将命令创建移出循环以提高效率。