c# - 从 (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”的结果到另一个地方
解决方案
您必须在更大的范围内声明 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;
}
推荐阅读
- python-2.7 - Elasticsearch DSL:过滤,然后在 python 中聚合
- microsoft-graph-api - 同步邮箱状态、增量与订阅的最佳实践
- modelica - 如何在块中使用未指定的数组维度?
- javascript - 使用参数行数据将数据表中的行数据传递给控制器中的方法
- c++ - 是否仅在主线程上接收回调?
- python - 将会话 ID 添加到我的散景应用程序确实会返回一个空白页
- javascript - PUT multipart-formdata 包含 PNG 和 XMLHttpRequest 在 vanilla javascript
- javascript - 在没有 jquery 的情况下滚动时更改导航栏内容(Header Sticky on Scroll)?
- javascript - 增加音量滑块感知线性的数学函数
- angular - 如何在 ionic 4 ion-list 中制作一些项目分隔符