I am trying to fetch the data in a decimal variable. I highly need your assistance to do so. if I test the query but put the fetched value in the label, it works without any problem. However, I want to get it in the decimal humidity as I want to compare this value with the threshold. Could you help me with this? Your help with being highly appreciated
below is the code
the output: I still get 20 which is the declared value in the code.
namespace IoTSmartFarming
{
public partial class DataVisualization : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
showHumidity();
}
private decimal getHumidity()
{
SqlConnection conn = new SqlConnection(strcon);
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
decimal humidity = 20;
SqlCommand cmd = new SqlCommand("SELECT TOP 1 value from Humidity ORDER BY time desc", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Label4.Text= dr.GetValue(0).ToString();
}
return humidity;
}
private void showHumidity()
{
decimal actHumidity = getHumidity();
Label4.Text = actHumidity.ToString();
if(actHumidity>100 || actHumidity < 10)
{
Label5.Visible = false;
Label6.Visible = true;
}
}
}
}
You forgot to assign your variable. All that you need is add an variable assignment:
humidity = dr.GetDecimal(0);
Related
First Process is to get value on database and search the Project Amount. after dislplaying it in amount.Text here is the code in search button
private void ButSearchGet_Click(object sender, EventArgs e)
{
if (textBox6.Text == "")
{
MessageBox.Show("Invalid Please Input Control #..");
clear2();
}
else
{
SqlCommand cmd = new SqlCommand("select * from tbl_expense WHERE Contract_ID Like'%' +#Contract_ID+ '%'", conn);
cmd.Parameters.AddWithValue("Contract_ID", textBox6.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;
this.datagridview.Columns["id"].Visible = false;
conn.Open();
SqlCommand cm = new SqlCommand("select * from tbl_expense where contract_id=#contract_id ", conn);
cm.Parameters.AddWithValue("contract_id", textBox6.Text);
SqlDataReader rdr;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
lblid.Text = rdr["CONTRACT_ID"].ToString();
lblcontractor.Text = rdr["CONTRACTOR"].ToString();
lblstatus.Text = rdr["PROJECT_STATUS"].ToString();
lblstart.Text = rdr["COVERED_PERIOD"].ToString();
lblend.Text = rdr["END_PERIOD"].ToString();
amount.Text = Convert.ToDecimal(rdr["PROJECT_AMOUNT"]).ToString("C", CultureInfo.CreateSpecificCulture("en-PH")); // here is the code to get decimal amount in database and throw to amount.Text it will display ex. ₱48,000,000.00
lblcons.Text = rdr["CONTRACT"].ToString();
label32.Text = rdr["id"].ToString();
projectid.Text = rdr["projectid"].ToString();
}
else
{
MessageBox.Show("No Data Exist");
clear2();
}
conn.Close();
refresh();
}
}
now the next step is to sum the project costs amount in the database i created a button to trigger function to sum all the project cost and display it to lblcost.Text. here is the code below
private void butGenerateExpense(object sender, EventArgs e)
{
decimal sum;
decimal subTotal = 0;
decimal subTotal1 = 0;
if (this.datagridview.Rows.Count > 0)
{
foreach (DataGridViewRow row in this.datagridview.Rows)
{
if (row.Cells[7].Value != null && !string.IsNullOrEmpty(row.Cells[7].Value.ToString()))
{
subTotal += Convert.ToDecimal(row.Cells[7].Value);
}
}
this.lbl1.Text = subTotal.ToString("C", CultureInfo.CreateSpecificCulture("en-PH"));
}
if (this.datagridview.Rows.Count > 0)
{
foreach (DataGridViewRow row in this.datagridview.Rows)
{
if (row.Cells[12].Value != null && !string.IsNullOrEmpty(row.Cells[12].Value.ToString()))
{
subTotal1 += Convert.ToDecimal(row.Cells[12].Value);
}
}
this.lbl2.Text = subTotal.ToString("C", CultureInfo.CreateSpecificCulture("en-PH"));
}
sum = subTotal + subTotal1;
textTotal.Text = sum.ToString("C", CultureInfo.CreateSpecificCulture("en-PH"));
Now it will display the total project cost in lblcost.Text after click the button to generate the expense.
here is my concern i want to Subtract the project Amount and project Cost and display the project Balance in the lblbalance.Text i want the the value and convert into decimal but i got this error and logic since it was being get search first in a process.
my first Code attempt is this.
private void butGenerateExpense(object sender, EventArgs e)
{
decimal a, b, diff;
a = Convert.ToDecimal(amount.Text);
b = Convert.ToDecimal(textTotal.Text);
diff = a - b;
lblbalance.Text = diff.ToString("C", CultureInfo.CreateSpecificCulture("en-PH"));
after pressing the button generate expense together with the codes to get the project cost.
The Error: System.FormatException: 'Input string was not in a correct format.'
If you convert the numbers to text using a specific culture, you need to use the same culture when parsing the text. See the TryParse overload that takes a IFormatProvider, i.e. a cultureInfo.
decimal.TryParse(textTotal.Text, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("en-PH"), out var result);
If you are converting strings to numbers for anything other than input or deserializing, or the other way around, you are doing something wrong. Try to keep the numbers as decimal values as long as possible. A common approach is to use a property with a backing field, with a setter that also updates the corresponding text-box.
Below these code I'm getting the wrong output in incrementing the string value in my Database column "SupplierID". I'm transferring the string value to my lbl_id in ADDSupplier Form and That's what i used to insert value to my "SupplierID".
Desired Output:
SPPL-0001
SPPL-0002
SPPL-0003
etc
Currently Output (Below these code):
SPPL-0001
SPPL-00012
SPPL-00013
etc
NOTE: When i repeat inserting data i get the currently output that i stated above but when i restart the program and the last inserted value, For example is SPPL-00013. When i open my adding form, lbl_id display the id as SPPL-0004. If i continue, it become SPPL-00045.
PS: SupplierID is varchar(50) in my database and also PRIMARY_KEY
These image shows the wrong output of mine
What i want to get help with is to correct my logic and get that desired output. Please help me. Thank you
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
public SIMSSupplier()
{
InitializeComponent();
}
public string ID = "SPPL-000";
public void GenerateAutoID()
{
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select Count(SupplierID) from admin_supplier", con))
{
int i = Convert.ToInt32(select.ExecuteScalar());
i++;
supply.lbl_id.Text = ID + i.ToString();
}
}
}
private void btn_register_Click(object sender, EventArgs e)
{
supply = new ADDSupplier(this);
supply.Show();
GenerateAutoID();
}
}
public partial class ADDSupplier : MetroForm
{
SIMSSupplier _view;
public ADDSupplier(SIMSSupplier _view)
{
InitializeComponent();
this._view = _view;
}
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
private void btn_ok_Click(object sender, EventArgs e)
{
_view.ID = lbl_id.Text;
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(txt_name.Text) || string.IsNullOrEmpty(txt_contact.Text) || string.IsNullOrEmpty(cbox_remark.Text) || string.IsNullOrEmpty(txt_address.Text))
{
CustomNotifcation.Show("Please input the required fields", CustomNotifcation.AlertType.warning);
}
else
{
using (var select = new SqlCommand("Insert into admin_supplier (SupplierID, Companyname, Contactnumber, Date, Remarks, Address) Values (#SupplierID, #Companyname, #Contactnumber, #Date, #Remarks, #Address)", con))
{
select.Parameters.Add("#SupplierID", SqlDbType.VarChar).Value = lbl_id.Text;
select.Parameters.Add("#Companyname", SqlDbType.VarChar).Value = txt_name.Text;
select.Parameters.Add("#Contactnumber", SqlDbType.VarChar).Value = txt_contact.Text;
select.Parameters.Add("#Date", SqlDbType.VarChar).Value = date;
select.Parameters.Add("#Remarks", SqlDbType.VarChar).Value = cbox_remark.Text;
select.Parameters.Add("#Address", SqlDbType.VarChar).Value = txt_address.Text;
select.ExecuteNonQuery();
CustomMessage.Show("Message: Supplier successfully added!", CustomMessage.Messagetype.Success2);
_view._Supplier();
}
}
}
}
}
You just need to use a format string instead:
string ID = "SPPL-"
supply.lbl_id.Text = ID + i.ToString("0000");
Which will result in the format being applied correctly. Right now you are appending the i variable to the ID, which is already SPPL-000, so the next one becomes SPPL-0001, etc.
I'm trying to save the unique value resulting from a query into a double variable, since the same is stored in the database as double, so I can later be able to multiply it with a counter, with the following code:
public partial class CoronaClaraCant : Form
{
private int conteoCliks = 0;
private string producto = "CoronaClara";
private double precio;
public CoronaClaraCant()
{
InitializeComponent();
}
private void CoronaClara_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;database=database;username=root;password=***");
conn.Open();
string select = "SELECT precio FROM productos where prodnom = '" + producto + "';";
MySqlCommand cmd = new MySqlCommand(select, conn);
double result = cmd.ExecuteNonQuery();
conteoCliks++;
precio = result;
double total = (precio * conteoCliks);
lblcantidad.Text = conteoCliks.ToString();
lblprecio.Text = precio.ToString();
lbltotal.Text = total.ToString();
}
}
So far I've only been getting negative values:
I'm guessing this could be because the ExecuteNonQuery, but I haven't been able to assign a double value to a ExecuteScalar method, and I'm not sure if there are other parameters I should consider when saving a double value into a variable.
You want to select data from database and you are calling ExecuteNonQuery which is used for Insert,Update or Delete commands.
You need to call ExecuteReader or if you want to get data in a DataTable you can fill a DataTable.
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
if (rdr.Read())
{
precio = (double)rdr["precio"];
}
}
I have little problem I am trying to add sequenced numbers in front the data that I will retrieve from a SQL Server database as shown below.
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Server=.;database=test;integrated security=false;user id=sa;pwd=#admin00");
SqlCommand com = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
com.CommandText = "select book_name from Table_book";
com.Connection = con;
con.Open();
dr = com.ExecuteReader();
while (dr.Read())
{
for (int i = 1; i <= dr.FieldCount; i++)
{
listBox1.Items.Add(i+"-"+dr[0].ToString());
i += i;
}
}
if (listBox1.Items.Count == 0)
{
MessageBox.Show("No Data Found");
}
dr.Close();
con.Close();
}
And the result will be like that:
TY all
I just use my server Id sequence to solve the problem like that:
SqlConnection con = new SqlConnection(#"server=.;database=test;integrated security=false;user id=sa;pwd=#admin00");
con.Open();
SqlCommand sqlcom = new SqlCommand("select book_id,book_name from Table_book", con);
SqlDataReader sqlDR=sqlcom.ExecuteReader();
while(sqlDR.Read())
{
listBox1.Items.Add(sqlDR["book_id"].ToString()+"-"+sqlDR["book_name"].ToString());
}
Add is capable of operating on objects, not just on strings.
Why?
class ModelClass {
// for use in algorithm, may be presented in GUI or not
int Sequence { get; set; }
string Description { get ; set ;}
// ... what You want, is is typical model class
override string ToString() {
// return what you want, is presented in GUI
return Descrition;
}
ModelClass( string n, int i ) ...
}
...
listBox.Items.Add( new ModelClass(i.ToString(), dr[...] // sequence )
Now you can check whatever you want from Items, because these are objects of ModelClass.
Code written by hand, non tested in IDE.
You're setting the "sequence number" to the number of fields returned in the results while iterating over each row with the dr.Read().
It's unnecessary for the for loop. What you should be doing is setting your counter variable outside of the dr.Read() and then incrementing it inside...
int i = 1;
while (dr.Read())
{
// set listbox item text
listBox1.Items.Add(i.ToString() + "-" + dr[0].ToString());
i+=1;
}
I have search a bunch for this and as you can tell I'm very new to C#, I I'm trying to learn this language.
So please forgive me if one of the 100 forms that I have looked at says the same thing that you post here.
I am trying to populate a list box with a the results from a stored procedure called LookupInvoices, this requires a parameter #InvoiceNumber that is an int.
I have a WPF that I would like to populate a listbox called lstResults with the results from this stored procedure.
Please look at my code and tell me where I have made an error, thanks so much for your time!
private void btnFill_Click(object sender, RoutedEventArgs e)
{
if (cmbInvoiceNumbers.SelectedItem == null)
{
System.Windows.MessageBox.Show("Please Choose A Invoice Number!");
return;
}
SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True");
int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());
cs.Open();
SqlCommand cmd = new SqlCommand("LookupInvoices", cs);
using (SqlDataReader reader = cmd.ExecuteReader())
{
SqlParameter pram = new SqlParameter("#invoiceNumber", invNumber);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pram);
cmd.Connection = cs;
reader.Read();
}
cs.Close();
}
Please not that when I click the button it crashes. This doesn't run all the way through.
You should put your all disposable elements (SqlConnection, SqlCommand, SqlDataReader) into using (....) { ...... } blocks, and you need to add the parameter before calling .ExecuteReader() - try this code:
public class InvoiceDto
{
public string Description { get; set; }
public int Hours { get; set; }
public decimal Amount { get; set; }
}
public void List<InvoiceDto> GetInvoiceData(int invoiceNumber)
{
List<InvoiceDto> data = new List<InvoiceData>();
using (SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.LookupInvoices", cs))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#invoiceNumber", SqlDbType.Int).Value = invoiceNumber;
cs.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
InvoiceDto dto = new InvoiceDto();
dto.Description = reader.GetFieldValue<string>(0);
dto.Hours = reader.GetFieldValue<int>(1);
dto.Amount = reader.GetFieldValue<decimal>(2);
data.Add(dto);
}
}
cs.Close();
}
return data;
}
and in your code-behind, you should call this method in your event handler
private void btnFill_Click(object sender, RoutedEventArgs e)
{
// get selected invoice number
int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());
// call method to get the data from the stored procedure
List<InvoiceDto> data = GetInvoiceData(invNumber);
// loop over the data and fill your listbox
foreach(InvoiceDto dto in data)
{
listbox.Items.Add(dto.Description);
}
}