根据SQL值更改公式
问题描述:
我有一个c#winforms应用程序根据公式进行一些计算。
公式运行正常但是根据sql表的值,公式可以改变。我正在考虑应用`IF',但如果我这样做,我点击按钮,公式什么都不做。
我删除了大量的代码以便于查看。
我尝试了什么:
Hi, i have a c# winforms app with makes some calculations based on a formula.
the formula runs OK but depending on the value of an sql table the formula can change. I was thinking of appying `IF´s`, but if i do i click the button and the formula does nothing.
I removed a large quantity of code to facilitade viewing.
What I have tried:
private void button1_Click(object sender, EventArgs e) //formula
{
decimal ValueFromDB;
con.Open();
using (SqlCommand cmd = new SqlCommand("select prumos from dbo.modelos where id = '" + prumos + "'", con))
{
cmd.Parameters.AddWithValue("@ID", prumos);
ValueFromDB = decimal.Parse(cmd.ExecuteScalar().ToString());
con.Close();
}
if (larg.Text == string.Empty)
{
MessageBox.Show("Missing Value", "Warning");
return;
//SEVERAL OTHER IF´s to prevent empty textboxes
}
else if (prumos == "1")
{
return;
}
decimal uw;
decimal ata;
decimal vi1;
...
decimal wmk4;
decimal wmk5;
decimal wmk6;
vi1 = decimal.Parse(textBox1.Text);
wmk3 = decimal.Parse(textBox12.Text);
wmk4 = decimal.Parse(textBox22.Text);
...
wmk5 = decimal.Parse(textBox17.Text);
wmk6 = decimal.Parse(textBox15.Text);
...
uw = (adp * ufa + adv * ug + perv * wmk) / ac;
answ.Text = (Math.Truncate(uw * 100) / 100).ToString();
{
else if (prumos == "2")
{
return;
}
我应用此规则后,为什么公式不会加载的任何想法?
提前谢谢。
any ideas why the formula wont load after i apply this rule?
Thanks in advance.
答
嗯...你没有改变该代码中prumos的值 - 甚至显示它最初设置的地方。
你从SQL读取一个值,但是你将它存储在ValueFromDB
中,你再也没有引用它。我怀疑你真的需要把它作为的一部分,如果
而不是promus
并且不要那样做SQL!永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。
Well...you don't change the value of "prumos" in that code - or even show where it's set originally.
You do read a value from SQL, but you store that inValueFromDB
which you never reference again. I'd suspect that you really need to look at that instead as part of yourif
rather thanpromus
And don't do SQL like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
if (larg.Text == string.Empty)
{
MessageBox.Show("Missing Value", "Warning");
return;
//SEVERAL OTHER IF´s to prevent empty textboxes
}
// In both cases it will return
else if (prumos.Equals("1") || prumos.Equals("2"))
{
return;
}
// Put your calculation in last Condition
else
{
decimal uw;
decimal ata;
decimal vi1;
decimal wmk4;
decimal wmk5;
decimal wmk6;
vi1 = decimal.Parse(textBox1.Text);
wmk3 = decimal.Parse(textBox12.Text);
wmk4 = decimal.Parse(textBox22.Text);
wmk5 = decimal.Parse(textBox17.Text);
wmk6 = decimal.Parse(textBox15.Text);
uw = (adp * ufa + adv * ug + perv * wmk) / ac;
answ.Text = (Math.Truncate(uw * 100) / 100).ToString();
}