我正在尝试创建一个布尔返回函数,该函数将检查文本框中的值,使用表中的datareader检查它是否找到匹配项,然后返回一个布尔值。我已经现在使用这个功能,它工作正常。
public Boolean testname()
{
Boolean test=false;
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\noewayout\Documents\Project.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("select CNAME from CUSTOMER", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string cname = "";
while (dr.Read())
{
cname = Convert.ToString(dr["CNAME"]);
if (cname == textBox1.Text.ToString())
{
test = true;
return test;
}
}
conn.Close();
return test;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{ MessageBox.Show("Please type in Customer Name"); }
else
{
Boolean boo = testname();
if (boo == false)
{
MessageBox.Show("Invalid Customer Name");
}
else if (boo == true)
{
try
{
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\noewayout\Documents\Project.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("select ONAME,PRICE,QTY from OIL_TYPE,SALEOIL,CUSTOMER where OIL_TYPE.OID=SALEOIL.OID and CUSTOMER.CID=SALEOIL.CID and CNAME='" + textBox1.Text.ToString() + "'", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
int qty = 0;
int price = 0;
string oname = "";
while (dr.Read())
{
oname = Convert.ToString(dr["ONAME"]);
qty = Convert.ToInt32(dr["QTY"]);
price = Convert.ToInt32(dr["PRICE"]);
int tcost = qty * price;
MessageBox.Show("Oil Name\t\tQuantity\tPrice\tTotal Cost\n" + oname + " \t" + qty + "\t" + price + "\t" + tcost);
}
conn.Close();
}
catch (SqlException) { MessageBox.Show("Error!!"); }
}
}
}
但过去几个小时我在使用这种简单的检查方法时遇到了麻烦。
public Boolean testname()
{
Boolean test = false;
SqlConnection conn = new SqlConnection(dbsource);
SqlCommand cmd = new SqlCommand("select Fid from Firearm", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string tfid = "";
while (dr.Read())
{
tfid = Convert.ToString(dr["Fid"]);
if (tfid == textBox6.Text.ToString())
{
test = true;
return test;
}
}
conn.Close();
return test;
}
private void searchbtn_Click(object sender, EventArgs e)
{
string mysql = "select * from Firearm where Fid= '" + textBox6.Text + "'";
if (textBox6.Text == "")
{ MessageBox.Show("Please fill the text field"); }
else
{
Boolean boo = testname();
if (boo == false)
{
MessageBox.Show("Invalid Fid");
}
else if (boo == true)
{
try
{
SqlConnection conn = new SqlConnection(dbsource);
SqlCommand cmd = new SqlCommand(mysql, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Show();
}
catch (SqlException) { MessageBox.Show("Error!!!"); }
}
}
}
即使我输入了正确的id值,它仍然会返回false。我已经尝试了所有我知道但仍然没有去的东西。任何帮助或建议都会很棒。谢谢
答案 0 :(得分:2)
尝试比较如下
{{1}}