【问题标题】:ASP.NET C# Changing connection strings based on drop down listASP.NET C#根据下拉列表更改连接字符串
【发布时间】:2015-10-27 09:45:24
【问题描述】:

我对 ASP.Net C# 还是很陌生,我有这段代码可以正常工作。我在 web.config 文件中有多个连接字符串,我根据下拉列表的文本在它们之间切换。我希望对任何更整洁/更清洁的方法提出一些建议来存档它,而不是我在下面(如果有的话)。谢谢!

 protected void search_ClickALL(object sender, EventArgs e)
{

    if (ddlALL.SelectedItem.Text == "ENWL")
    {
        using (
       SqlConnection conn =
           new SqlConnection(ConfigurationManager.ConnectionStrings["ConHprENWL"].ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT dpCreatedDT, enStatusCH, enNotificationNoNI FROM dp_enquiry WHERE ennotificationnoni = @JobnoALL", conn);
            try
            {
                SqlParameter search = new SqlParameter();
                search.ParameterName = "@JobnoALL";
                search.Value = JobnoALL.Text.Trim();
                cmd.Parameters.Add(search);
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                gridviewALL.DataSource = dt;
                gridviewALL.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                if (cmd.ExecuteScalar() == null)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Job Number not found!');</script>");
                }
                conn.Close();
                mpePopUpALL.Show();
            }
        }
    }

    else if (ddlALL.SelectedItem.Text == "NW")
    {
        using (
       SqlConnection conn =
           new SqlConnection(ConfigurationManager.ConnectionStrings["ConHprNorthumbrian"].ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT dpCreatedDT, enStatusCH, enNotificationNoNI FROM dp_enquiry WHERE ennotificationnoni = @JobnoALL", conn);
            try
            {
                SqlParameter search = new SqlParameter();
                search.ParameterName = "@JobnoALL";
                search.Value = JobnoALL.Text.Trim();
                cmd.Parameters.Add(search);
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                gridviewALL.DataSource = dt;
                gridviewALL.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                if (cmd.ExecuteScalar() == null)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Job Number not found!');</script>");
                }
                conn.Close();
                mpePopUpALL.Show();
            }
        }
    }


    }

【问题讨论】:

    标签: c# asp.net connection-string dropdown


    【解决方案1】:

    创建一个单独的函数并在其中写入所有业务逻辑,并根据下拉项获取连接字符串作为参数

    protected void search_ClickALL(object sender, EventArgs e)
    {
        if (ddlALL.SelectedItem.Text == "ENWL")
        {
            ShowData(ConfigurationManager.ConnectionStrings["ConHprENWL"].ConnectionString.ToString());
        }
        else if (ddlALL.SelectedItem.Text == "NW")
        {
            ShowData(ConfigurationManager.ConnectionStrings["ConHprNorthumbrian"].ConnectionString).ToString());
        }
    }
    
    private void ShowData(string connectionstring)
    {
        using (
           SqlConnection conn =
               new SqlConnection(connectionstring))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT dpCreatedDT, enStatusCH, enNotificationNoNI FROM dp_enquiry WHERE ennotificationnoni = @JobnoALL", conn);
                try
                {
                    SqlParameter search = new SqlParameter();
                    search.ParameterName = "@JobnoALL";
                    search.Value = JobnoALL.Text.Trim();
                    cmd.Parameters.Add(search);
                    SqlDataReader dr = cmd.ExecuteReader();
                    DataTable dt = new DataTable();
                    dt.Load(dr);
                    gridviewALL.DataSource = dt;
                    gridviewALL.DataBind();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    if (cmd.ExecuteScalar() == null)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Job Number not found!');</script>");
                    }
                    conn.Close();
                    mpePopUpALL.Show();
                }
           }
    }
    

    【讨论】:

    • 谢谢!这正是我想要的
    • @LiranBo: ddlALL.SelectedItem.Text 可能与ConnectionStrings 密钥不同。在 OP 帖子中仔细查看它们可能会有所不同,文本是 ENWL 但连接字符串键是 ConHprENWL 不同。
    • 为了使用ddlALL.SelectedItem.Text,您必须在 web.config 中的下拉文本和连接字符串键中具有完全相同的名称。
    【解决方案2】:

    您正在编写相同的代码,多次使用Switch 案例可以一次完成

         string ConnectionString;
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    ConnectionString = ConfigurationManager.ConnectionStrings["ConHprENWL"].ConnectionString
                    break;
                case 1:
                    ConnectionString = ConfigurationManager.ConnectionStrings["XYZ"].ConnectionString
                    break;
    
            }
            SqlConnection Con = new SqlConnection(ConnectionString);
            Con.Open();  
    /*YOUR CODE */
    

    【讨论】:

      【解决方案3】:

      您正在执行以下操作两次:

             conn.Open();
              SqlCommand cmd = new SqlCommand("SELECT dpCreatedDT, enStatusCH, enNotificationNoNI FROM dp_enquiry WHERE ennotificationnoni = @JobnoALL", conn);
      
       try
              {
                  SqlParameter search = new SqlParameter();
                  search.ParameterName = "@JobnoALL";
                  search.Value = JobnoALL.Text.Trim();
                  cmd.Parameters.Add(search);
                  SqlDataReader dr = cmd.ExecuteReader();
                  DataTable dt = new DataTable();
                  dt.Load(dr);
                  gridviewALL.DataSource = dt;
                  gridviewALL.DataBind();
              }
              catch (Exception ex)
              {
                  Response.Write(ex.Message);
              }
              finally
              {
                  if (cmd.ExecuteScalar() == null)
                  {
                      Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Job Number not found!');</script>");
                  }
                  conn.Close();
                  mpePopUpALL.Show();
              }
      

      改为将其作为函数并将您的 SQLConnection conn 作为参数传递给函数。

      同样当你使用 using 语句时,你不需要关闭 conn。

      【讨论】:

        【解决方案4】:

        也许只是使用 if 来选择连接字符串,因为其余的看起来都一样。

        protected void search_ClickALL(object sender, EventArgs e)
        {
         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ddlALL.SelectedItem.Text].ConnectionString))
         {
             conn.Open();
             SqlCommand cmd = new SqlCommand("SELECT dpCreatedDT, enStatusCH, enNotificationNoNI FROM dp_enquiry WHERE ennotificationnoni = @JobnoALL", conn);
             try
             {
                 SqlParameter search = new SqlParameter();
                 search.ParameterName = "@JobnoALL";
                 search.Value = JobnoALL.Text.Trim();
                 cmd.Parameters.Add(search);
                 SqlDataReader dr = cmd.ExecuteReader();
                 DataTable dt = new DataTable();
                 dt.Load(dr);
                 gridviewALL.DataSource = dt;
                 gridviewALL.DataBind();
             }
             catch (Exception ex)
             {
                 Response.Write(ex.Message);
             }
             finally
             {
                 if (cmd.ExecuteScalar() == null)
                 {
                     Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Job Number not found!');</script>");
                 }
                 conn.Close();
                 mpePopUpALL.Show();
             }
          }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多