I have the codes below that will display data from access database into textboxes of another form.
item items = new item();
Add_Order addorder = new Add_Order();
OleDbCommand cmd = new OleDbCommand("Select * from tblItems WHERE ItemName = #Item", connection);
cmd.Parameters.AddWithValue("#Item", items.ItemName1);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#ItemID", addorder.tbItemID.Text);
cmd.Parameters.AddWithValue("#ItemName", addorder.tbName.Text);
cmd.Parameters.AddWithValue("#ItemPrice", addorder.tbPrice.Text);
OleDbDataReader read = cmd.ExecuteReader();
while (read.Read())
{
addorder.tbItemID.Text = read[0].ToString();
addorder.tbName.Text = read[1].ToString();
addorder.tbPrice.Text = read[2].ToString();
}
addorder.ShowDialog();
connection.Close();
the error says that
Parameter #Item has no default value
But I already assigned the value of #Item in this line
cmd.Parameters.AddWithValue("#Item", items.ItemName1);
I found some mistakes, you are retrieving some items. Then, Why you are using ExecuteNonquery() and some other parameters. Simply try this
cmd.Connection = connection;
connection.Open();
OleDbCommand cmd = new OleDbCommand("Select * from tblItems WHERE ItemName = #Item", connection);
cmd.Parameters.AddWithValue("#Item", items.ItemName1);
OleDbDataReader read = cmd.ExecuteReader();
while (read.Read())
{
addorder.tbItemID.Text = read[0].ToString();
addorder.tbName.Text = read[1].ToString();
addorder.tbPrice.Text = read[2].ToString();
}
connection.Close();
Make sure that items.ItemName1 has a valid entry. You can verify this by simply passing some values manually as
cmd.Parameters.AddWithValue("#Item", "some text");
Try this one:
cmd.Parameters.AddWithValue("#Item", OleDbType.VarChar).Value = items.ItemName1;
And why are you using this again after ExecuteNonQuery()..?
cmd.Parameters.AddWithValue("#ItemID", addorder.tbItemID.Text);
cmd.Parameters.AddWithValue("#ItemName", addorder.tbName.Text);
cmd.Parameters.AddWithValue("#ItemPrice", addorder.tbPrice.Text);
cmd.Parameters.Add(new OleDbParameter("item", OleDbType.VarChar, 32, "Item").Value = items.ItemName1;
^^^^^^^^^^^^^^^^^^
the point is to construct Parameter()
Related
I want to update calorie_tracker table after burned value is calculated.Until cmd2 command it works.But while trying to cmd2 gives an error :Object reference not set to an instance of an object.How can I make this update in the same command(cmd) or is there any alternative?
string time = DateTime.Now.ToString("dd-MM-yyyy");
int burned = 0;
string s = (comboBox1.SelectedItem).ToString();
cnn.Open();
string cmdText = #"SELECT calorificValue
FROM myfitsecret.food
WHERE name=#name;
SELECT daily_gained
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using (MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.String).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.String).Value = Login.userID;
using (MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if (reader.Read()) burned += (Convert.ToInt32(reader[0])*int.Parse(textBox1.Text));
// if there is a second resultset, go there
if (reader.NextResult())
if (reader.Read())
burned += Convert.ToInt32(reader[0]);
}
cmd.Connection.Close();
MySqlCommand cmd2 = new MySqlCommand("update myfitsecret.calorie_tracker set daily_gained=#daily_gained where sportsman_id=#sportsman_id and Date=#Date");
cmd2.CommandType = CommandType.Text;
cmd2.Connection.Open();
cmd2.Parameters.AddWithValue("#daily_gained", burned);
cmd2.Parameters.AddWithValue("#Date", time);
cmd2.Parameters.Add("#sportsman_id", MySqlDbType.String).Value = Login.userID;
cmd2.ExecuteNonQuery();
You need to pass the connection to MySqlCommand before trying to open it like this:
cmd.Connection.Close();
MySqlCommand cmd2 = new MySqlCommand("update myfitsecret.calorie_tracker set daily_gained=#daily_gained where sportsman_id=#sportsman_id and Date=#Date",cnn);
cmd2.CommandType = CommandType.Text;
cmd2.Connection.Open();
I would also advise wrapping this command in a using statement as well.
I have a database (SQL server) and I added it into my webpage project but the problem is I cannot display the data in a gridview.
Here is my code:
string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
reader = SqlCommand.ExecuteReader();
GridView2.DataSource = reader;
GridView2.DataBind();
Change this
query = string.Format("select * from table where clumn='"+s+"' ", s);
to this
query = string.Format("select * from table where clumn='{0}' ", s);
Use SqlParameters instead of manipulating a string as you are doing now.
Also, use using statement to dispose objects correctly.
Don't use select * because it will affect performance, only select the columns needed.
Here an example of your code, modified:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=#column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}
better use SqlDatadapter:
DataTable dt = new DataTable();
...
using (SqlDataAdapter a = new SqlDataAdapter( new SqlCommand(query, conn)))
{
GridView2.DataSource =a.Fill(dt).AsDataView();
}
MyCmd = new MySqlCommand("SELECT FnGetTransDate()", MyCon);
MyCon.Open();
MyRead = MyCmd.ExecuteReader();
MyRead.Read();
transdate = Convert.ToDateTime(MyRead.GetValue(0).ToString());
MyRead.Close();
MyCmd = new MySqlCommand("SpGenProcess", MyCon);
MyCmd.CommandType = CommandType.StoredProcedure;
MyCmd.Parameters.AddWithValue("#tempprocessidlist", idlist);
MyCmd.Parameters.AddWithValue("#prdate",Convert.ToDateTime(transdate.ToShortDateString()));
MyCmd.Parameters.AddWithValue("#out_status", MySqlDbType.Int32);
MyCmd.Parameters.AddWithValue("#out_msg", MySqlDbType.VarChar);
MyCmd.Parameters["#out_status"].Direction = ParameterDirection.Output;
MyCmd.Parameters["#out_msg"].Direction = ParameterDirection.Output;
MyCmd.ExecuteNonQuery();
int.TryParse(MyCmd.Parameters["#out_status"].Value.ToString(), out outstatus);
ErMsg = MyCmd.Parameters["#out_msg"].Value.ToString();
While Executing the statement 'MyCMd.ExecuteNonQuery()' getting error Inupt string was not in correct format ?? [Error On Line ExecuteNonQuery]
Use ExecuteReader if you need to read the values from the reader
var reader = MyCmd.ExecuteReader();
if (reader.HasRows)
{
if (reader.Read())
{
int status = (int)reader["out_status"];//breakpoint here
string msg = (string)reader["out_msg"]; //here also
}
}
This is my code on my FormLoad-event
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
I want two options to populate an autocomplete textbox during typing in textbox:
By name
By number
However it doesn't work. I already tryed this in my TextChanged-event, but with no luck. Can somebody help me?
Rather than using optional AutoCompleteSource update all the data into one source. This wont be any problem, since the person wont have to select the options, rather he will type by deciding his option.
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
dReader = cmd.ExecuteReader();
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
or if you want to use the older option,
namesCollection.RemoveAll();
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
namesCollection.RemoveAll();
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
Notice
namesCollection.RemoveAll();
I have a table of CheckBoxes that are inserted into a SQL db as '1' and '0'. However, I would like to retrieve those values again with a load event, but I'm not able to get them. This is my code:
private void getAuditChecklist()
{
SqlCommand cmd = null;
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string queryString = #"SELECT Mount, Braker, Access, Conn_Net, Log_Book, Pictures, Floor, Cb_Lenght, Channel FROM AUDITOR_CHECKLIST " +
"WHERE SITE_ID = #SiteID";
using (SqlConnection connection =
new SqlConnection(conn))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter("#SiteID", //the name of the parameter to map
System.Data.SqlDbType.NVarChar, //SqlDbType value
20, //The width of the parameter
"SITE_ID")); //The name of the column source
//Fill the parameter with the value retrieved
//from the text field
cmd.Parameters["#SiteID"].Value = foo.Site_ID;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CheckBox1.Checked = (reader.GetBoolean(reader.GetOrdinal("Mount")));
CheckBox2.Checked = (reader.GetBoolean(reader.GetOrdinal("Braker")));
CheckBox3.Checked = (reader.GetBoolean(reader.GetOrdinal("Access")));
CheckBox4.Checked = (reader.GetBoolean(reader.GetOrdinal("Conn_Net")));
CheckBox5.Checked = (reader.GetBoolean(reader.GetOrdinal("Log_Book")));
CheckBox6.Checked = (reader.GetBoolean(reader.GetOrdinal("Pictures")));
CheckBox8.Checked = (reader.GetBoolean(reader.GetOrdinal("Floor")));
CheckBox9.Checked = (reader.GetBoolean(reader.GetOrdinal("Cb_lenght")));
CheckBox10.Checked = (reader.GetBoolean(reader.GetOrdinal("Channel")));
}
reader.Close();
}
}
What am I missing to get the checkmark from the sql db? Below is how insert into sql:
private void SaveAuditChecklist()
{
if (auditChecklist != null)
{
SqlCommand cmd = null;
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string queryString = #"INSERT INTO AUDITOR_CHECKLIST VALUES(" +
"#SiteID, #Mount, #Braker, #Access, #ConnNet, #LogBook, #Pictures, #Floor, #CbLenght, #Channel) ";
using (SqlConnection connection =
new SqlConnection(conn))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter(
"#SiteID", //the name of the parameter to map
System.Data.SqlDbType.NVarChar, //SqlDbType value
20, //The width of the parameter
"Site_ID")); //The name of the column source
//Fill the parameter with the value retrieved
//from the text field
cmd.Parameters["#SiteID"].Value = foo.Site_ID;
cmd.Parameters.Add(new SqlParameter("#Mount", SqlDbType.Bit));
cmd.Parameters["#Mount"].Value = CheckBox1.Checked;
cmd.Parameters.Add(new SqlParameter("#Braker", SqlDbType.Bit));
cmd.Parameters["#Braker"].Value = CheckBox2.Checked;
cmd.Parameters.Add(new SqlParameter("#Access", SqlDbType.Bit));
cmd.Parameters["#Access"].Value = CheckBox3.Checked;
cmd.Parameters.Add(new SqlParameter("#ConnNet", SqlDbType.Bit));
cmd.Parameters["#ConnNet"].Value = CheckBox4.Checked;
cmd.Parameters.Add(new SqlParameter("#LogBook", SqlDbType.Bit));
cmd.Parameters["#LogBook"].Value = CheckBox5.Checked;
cmd.Parameters.Add(new SqlParameter("#Pictures", SqlDbType.Bit));
cmd.Parameters["#Pictures"].Value = CheckBox6.Checked;
cmd.Parameters.Add(new SqlParameter("#Floor", SqlDbType.Bit));
cmd.Parameters["#Floor"].Value = CheckBox8.Checked;
cmd.Parameters.Add(new SqlParameter("#CbLenght", SqlDbType.Bit));
cmd.Parameters["#CbLenght"].Value = CheckBox9.Checked;
cmd.Parameters.Add(new SqlParameter("#Channel", SqlDbType.Bit));
cmd.Parameters["#Channel"].Value = CheckBox10.Checked;
cmd.ExecuteReader();
}
}
}
Booleans are stored as 1 or 0 in Sql Database, but the datareader do the conversion for you. Instead use:
var myBool = reader.GetBoolean(i);
Then just assign the value to the control's value property.
Finally got the reader they way it should work to get the checkmark values. I edited my question with the working code; however, below is what I added or changed for the reader:
while (reader.Read())
{
CheckBox1.Checked = (reader.GetBoolean(reader.GetOrdinal("Mount")));
CheckBox2.Checked = (reader.GetBoolean(reader.GetOrdinal("Braker")));
CheckBox3.Checked = (reader.GetBoolean(reader.GetOrdinal("Access")));
CheckBox4.Checked = (reader.GetBoolean(reader.GetOrdinal("Conn_Net")));
CheckBox5.Checked = (reader.GetBoolean(reader.GetOrdinal("Log_Book")));
CheckBox6.Checked = (reader.GetBoolean(reader.GetOrdinal("Pictures")));
CheckBox8.Checked = (reader.GetBoolean(reader.GetOrdinal("Floor")));
CheckBox9.Checked = (reader.GetBoolean(reader.GetOrdinal("Cb_lenght")));
CheckBox10.Checked = (reader.GetBoolean(reader.GetOrdinal("Channel")));
}