草庐IT

c# - C# 新手 - 尝试编写代码来执行简单的功能

coder 2023-10-04 原文

我是 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 以及提交的评论。

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

最佳答案

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

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 block 正在设置 FormMessage.Text 值 bot 不退出该方法,因此该方法在 catch block 结束的地方继续执行,重置 文本 值并显示未抛出异常。

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

使这类问题更容易被捕获的一些通用指南:

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

关于c# - C# 新手 - 尝试编写代码来执行简单的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12934456/

有关c# - C# 新手 - 尝试编写代码来执行简单的功能的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  5. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  6. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  7. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  8. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  9. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  10. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

随机推荐