[英]C# winforms Why messageboxes dont work with IF for DataReader
我刚刚用 C#(winforms) VS2019 编写了我的第一个程序。 到目前为止,一切都很好,但我卡在这里。 在下面的代码中,我尝试
现在,我有两个主要问题
首先 - 我试图检查,如果表 3 的 select 确实有效,但没有出现带有 id 的测试消息框(如果有效,消息将更改为 sql 删除)
第二 - 如果数据库中不存在字符串,则应该抛出“未找到”的消息框在 VS 中出错:无法分配给“显示”,因为它是“方法组”
这里有什么问题?
private void btMagClear_Click(object sender, EventArgs e)
{
string connectionString = $@"Data Source={tbSerwer.Text}; Initial Catalog={tbBaza.Text};User ID={tbLogin.Text}; Password={tbPassword.Text}";
try
{
SqlConnection sqlConnection;
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
string DataMa = dtDataClear.Value.Year.ToString() + dtDataClear.Value.Month.ToString() + dtDataClear.Value.Day.ToString();
if (string.IsNullOrWhiteSpace(tbMagClear.Text))
{
SqlCommand cmd = new SqlCommand($@"delete from TABLE where CODE not in (select CODE from TABLE2 where DATA > '{DataMa}' )", sqlConnection);
cmd.ExecuteNonQuery();
}
else
{
SqlCommand sqlCommandSelect;
SqlDataReader sqlDataReader;
string sqlSelect = "";
sqlSelect = $@"select id from TABLE3 where CODE2 = '{tbMagClear.Text}'";
sqlCommandSelect = new SqlCommand(sqlSelect, sqlConnection);
sqlDataReader = sqlCommandSelect.ExecuteReader();
int MagID = sqlDataReader.GetInt32(0);
if (sqlDataReader.HasRows)
{
MessageBox.Show(Convert.ToString(MagID));
}
else
{
MessageBox.Show = ("Not Found");
}
sqlDataReader.Close();
sqlCommandSelect.Dispose();
}
// MessageBox.Show(DataMa);
}
catch (Exception)
{
}
}
好的,我明白了,谢谢大家-第二个问题确实是我的失明
至于 DataReader 的问题,读取异常非常棒;)“不存在数据时尝试读取无效”,因此此代码有效:
sqlCommandSelect = new SqlCommand(sqlSelect, sqlConnection);
sqlDataReader = sqlCommandSelect.ExecuteReader();
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
MessageBox.Show(Convert.ToString(sqlDataReader.GetInt32(0)));
}
}
else
{
MessageBox.Show("Not Found");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.