首页 > 解决方案 > 从 (dr.Reader()) {} 获取数据

问题描述

我为“selectedIndexChanged”事件中的组合框编写了一个程序,以获得最大的“REC”数。所以我遇到了一些导致“最终”结果的问题。我将字符串变量定义为“字符串 x”和“字符串最大值”。我需要得到'finally'段的结果,但它给了我一些错误,因为'该名称在'当前上下文'中不存在。请帮我调试一下

  try
             {                
                 con.Open();
                 SqlCommand cmd = new SqlCommand("Proc_New_check", con);
                 SqlDataAdapter sda = new SqlDataAdapter(cmd);
                 cmd.Parameters.Add("@PMNo", SqlDbType.VarChar, 50).Value = comboBox1.Text.Trim();
                 sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                 DataTable dt = new DataTable();
                 sda.Fill(dt);
                 string n = dt.Rows[0][0].ToString();

                 SqlCommand cmd1 = new SqlCommand("select Cmbl from tbl2 where records='" +       
                   comboBox1.Text + "'", con);
                 SqlDataReader dr = cmd.ExecuteReader();
                 if (dr.Read())
                {
                     string X = dr["Cmbl"].ToString();
                }

                 string max = X +n;

                 con.Close();
             }
             catch (SqlException exc)
             {
                 MessageBox.Show("Error" + exc);
             }
             finally
             {
                 string REC = max;                  
                 textBox1.Text = REC;                
             }

我希望得到结果

(字符串最大值 = AB 00001)

但是 X 和 max 会出错。

如何从数据阅读器中获取“X”的结果到另一个地方

标签: c#

解决方案


您必须在更大的范围内声明 max 和 X :

string max = string.Empty;
try
{                
     con.Open();
     SqlCommand cmd = new SqlCommand("Proc_New_check", con);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     cmd.Parameters.Add("@PMNo", SqlDbType.VarChar, 50).Value = comboBox1.Text.Trim();
     sda.SelectCommand.CommandType = CommandType.StoredProcedure;
     DataTable dt = new DataTable();
     sda.Fill(dt);
     string n = dt.Rows[0][0].ToString();

     SqlCommand cmd1 = new SqlCommand("select Cmbl from tbl2 where records='" + comboBox1.Text + "'", con);
     SqlDataReader dr = cmd.ExecuteReader();

     string X = string.Empty;         
     if (dr.Read())
     {
         X = dr["Cmbl"].ToString();
     }

     max = X +n;

     con.Close();
 }
 catch (SqlException exc)
 {
     MessageBox.Show("Error" + exc);
 }
 finally
 {
     string REC = max;                  
     textBox1.Text = REC;                
 }

推荐阅读