5

我是 C# 新手(在 PHP、Python 和 Javascript 中工作),我正在尝试或多或少地复制另一个页面并更改一些内容 - 提交表单和数据库。

无论如何,这是代码:

public partial class commenter : System.Web.UI.Page
{

    string employee_reviewed;
    //public Commenter();
    public void SaveBtn_Click(object sender, EventArgs e)
    {
        if (CommentTB.Text == "Please enter a comment.")
        {
            String csname = "Email Error";
            Type cstype = this.GetType();
            ClientScriptManager cs = Page.ClientScript;
            if (!cs.IsStartupScriptRegistered(cstype, csname))
            {
                String cstext = "alert('Please submit at least one comment.');";
                cs.RegisterStartupScript(cstype, csname, cstext, true);
            }
            FormMessage.Text = "Please submit at least one comment.";
            return;
        }
        string comment = CommentTB.Text;
        comment = comment.Replace("'", "''");
        comment = comment.Replace("’", "''");
        comment = comment.Replace("`", "''");

        try
        {
            //myCommand.Connection.Open();
            //myCommand.ExecuteNonQuery();
            //myCommand.Connection.Close();

            MySqlCommand myCommand;
            MySqlConnection connection;
            string connStringName = "server=localhost;database=hourtracking;uid=username;password=password";
            connection = new MySqlConnection(connStringName);

            string sql_query;


            sql_query = "insert into peer_review_comment " + " (emp_id,  comment)" + " values(?employeeid, ?comment) ";

            //String csname = "Email Error";
            //Type cstype = this.GetType();
            //ClientScriptManager cs = Page.ClientScript;
            //cs.RegisterStartupScript(cstype, csname, sql_query, true);
            myCommand = new MySqlCommand(sql_query, connection);
            //FormMessage.Text = sql_query;
            //return;

            Trace.Write("comment = ", comment);
            myCommand.Parameters.Add(new MySqlParameter("?employeeid", ViewState["employeeid"].ToString()));
            myCommand.Parameters.Add(new MySqlParameter("?comment", comment));

            try
            {
                myCommand.Connection.Open();
                myCommand.ExecuteNonQuery();
                myCommand.Connection.Close();
            }
            catch (Exception ex)
            {
                FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
            }
            //SendNotification(from, to, cc, subject, body, attach);
            FormMessage.Text = "\n Thank you for leaving anonymous feedback for " + employee_reviewed; ;
            ThankyouDiv.Visible = true;
            FormFieldDiv.Visible = false;
            reviewHeader.Visible = false;
        }
        catch (Exception ex)
        {
            FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
        }
    }
}

我真的不知道我在做什么 - 我正在阅读教程,但 C# 是一种与我习惯的语言截然不同的语言。

当我当前不更改文本但提交不起作用时,我收到 Javascript 警报 - 我希望它提交到peer_review_comment数据库表,并填写employeeid 以及提交的评论。

抱歉,如果我的理解如此参差不齐,我是一个 TOTAL C# 新手(目前正在阅读http://www.csharp-station.com/Tutorial/CSharp/

4

2 回答 2

7

我的猜测是问题出在这里:

try
{
    myCommand.Connection.Open();
    myCommand.ExecuteNonQuery();
    myCommand.Connection.Close();
}
catch (Exception ex)
{
    FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message;
    // no "return;"  !!
}
//SendNotification(from, to, cc, subject, body, attach);
FormMessage.Text = "\n Thank you for leaving anonymous feedback for " + 
                        employee_reviewed; ;

您的catch块正在设置FormMessage.Text值 bot 不退出该方法,因此该方法在 catch 块完成的地方继续执行,重置该Text值并显示没有引发异常。

return;在 catch 块的末尾添加一个以查看异常消息。

一些使此类问题更容易被捕获的一般准则:

  • 不要试图在一种方法中做太多事情。有一种方法来验证消息(或者在客户端使用Validators,另一种方法来进行 DB 调用,等等。
  • 学习使用调试器。您可以单步执行代码并更好地了解导致此类错误的原因。
  • 除非您可以对异常做点什么,否则让它们冒泡到更高级别的事件处理程序(如Elmah)并没有什么坏处,这样异常就不会像这里那样被意外吞没。一般来说,最好在较低级别的方法中重新抛出异常(可能添加一些上下文或用户友好的消息),以便较高级别的异常处理可以决定做什么(显示消息、日志等)
于 2012-10-17T12:43:33.760 回答
0

我冒昧地重构了您的代码。这显示了一些更好的代码实践,但也可能向您显示问题。除了这些代码更改,我还建议阅读 D. Stanley 的答案;那里也有一些有用的提示。

if (CommentTB.Text == "Please enter a comment.") 
{ 
    String csname = "Email Error"; 
    Type cstype = this.GetType(); 
    ClientScriptManager cs = Page.ClientScript; 
    if (!cs.IsStartupScriptRegistered(cstype, csname)) 
    { 
        String cstext = "alert('Please submit at least one comment.');"; 
        cs.RegisterStartupScript(cstype, csname, cstext, true); 
    } 
    FormMessage.Text = "Please submit at least one comment."; 
    return; 
} 

// This helps some but very little, just wanted to show an alternative to writing three statements
string comment = CommentTB.Text.Replace("'", "''").Replace("’", "''").Replace("`", "''"); 
//string comment = CommentTB.Text; 
//comment = comment.Replace("'", "''"); 
//comment = comment.Replace("’", "''"); 
//comment = comment.Replace("`", "''"); 


try 
{ 
    // No need to do string concatenation...just make it one string.
    // sql_query = "insert into peer_review_comment " + " (emp_id,  comment)" + " values(?employeeid, ?comment) "; 
    string sql_query = "insert into peer_review_comment (emp_id,  comment) values (?employeeid, ?comment) "; 

    string connStringName = "server=localhost;database=hourtracking;uid=username;password=password"; 

    // Use a "using" clause because it guarantees the connection is closed even when an exception occurs.
    using (MySqlConnection connection = new MySqlConnection(connStringName)) 
    {
        connection.Open(); 

        // Again, use a "using" clause
        using (MySqlCommand myCommand = new MySqlCommand(sql_query, connection)) 
        {
            Trace.Write("comment = ", comment); 
            myCommand.Parameters.Add(new MySqlParameter("?employeeid", ViewState["employeeid"].ToString())); 
            myCommand.Parameters.Add(new MySqlParameter("?comment", comment)); 
            myCommand.ExecuteNonQuery(); 

            // No need for a Close statement with "using" clause.
            //myCommand.Connection.Close(); 
        }
    } 

    FormMessage.Text = "\n Thank you for leaving anonymous feedback for " + employee_reviewed;
    ThankyouDiv.Visible = true; 
    FormFieldDiv.Visible = false; 
    reviewHeader.Visible = false; 
}
catch (Exception ex) 
{ 
    FormMessage.Text = "Error:SaveBtn_Click - " + ex.Message; 
} 
于 2012-10-17T13:15:52.817 回答