Im writing stock program - just to learn a little bit of c# and i got some problem.
Here is a part of mine code
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
string conString =
"Data Source=192.168.0.195;" +
"Initial Catalog=test;" +
"User id=sa;" +
"Password=12345678;";
string query = "Select * from dokumenty where symbol='" + comboBox_symbol.Text + "' ; ";
SqlConnection conDB = new SqlConnection(conString);
SqlCommand cmdDB = new SqlCommand(query, conDB);
SqlDataReader sqlReader;
try
{
conDB.Open();
sqlReader = cmdDB.ExecuteReader();
while (sqlReader.Read())
{
var s_Typ_dok = sqlReader.GetString(1);
var s_Symbol = sqlReader.GetString(2);
var s_Delivery_date = sqlReader.GetString(3);
var s_Invoice_date = sqlReader.GetString(4);
var s_Invoice_nr = sqlReader.GetInt32(5).ToString();
var s_Sybtype = sqlReader.GetString(6);
var s_Produkt_index = sqlReader.GetString(7);
var s_Produkt_name = sqlReader.GetString(8);
var s_Quantity = sqlReader.GetInt32(9).ToString();
var s_Price = sqlReader.GetString(10);
var s_From_warehouse = sqlReader.GetString(12);
var s_To_warehouse = sqlReader.GetString(13);
var s_Currency = sqlReader.GetString(14);
var s_Supplier_reciever = sqlReader.GetString(15);
comboBox_Type.Text = s_Typ_dok;
textBox_symbol.Text = s_Symbol;
textBox_deliveryDate.Text = s_Delivery_date;
textBox_invoiceDate.Text = s_Invoice_date;
textBox_invoice.Text = s_Invoice_nr;
textBox_subtype.Text = s_Sybtype;
textBox_produkt_index.Text = s_Produkt_index;
textBox_name.Text = s_Produkt_name;
textBox_quantity.Text = s_Quantity;
textBox_price.Text = s_Price;
comboBox_from_warehouse.Text = s_From_warehouse;
comboBox_to_warehouse.Text = s_To_warehouse;
comboBox_currency.Text = s_Currency;
textBox_supplier.Text = s_Supplier_reciever;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
which works ok, when i selected something in combobox5 it auto insert things to Textboxes when it exist in DB, but when i erase this thing which i select in combobox5, text in textboxes is still there. Is there any chance to erase it when combobox5 == null?
On SelectedIndexChanged event add one condition to check SelectedIndex==0, if selected index is zero then clear text of Text box,
If you don't wants to edit text from combo box then you can set combobox as non editable by setting
comboBox5.DropDownStyle = ComboBoxStyle.DropDownList;
This will not allow user to edit text from combobox
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox5.SelectedIndex==0)
{
TextBoxId.Text=String.Empty;
}
else
{
//Rest of your code here
}
}
Related
When I'm trying to retrieve my image by combo box there show the massage . Parameter not valid
I was try many way but problem is same ..
Every time I run the code below, I get same massage.
private void cBoxSearch_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con = ConnectionController.GetInstance().GetConnection();
con.Open();
com = new SQLiteCommand("SELECT * FROM Stock WHERE ProductName = '" + cBoxSearch.Text + "' ", con);
myReader = com.ExecuteReader();
product prod = new product();
while (myReader.Read())
{
prod.proid = myReader[0].ToString();
prod.prodname = myReader[1].ToString();
prod.proMdl = myReader[2].ToString();
prod.serialN = myReader[3].ToString();
prod.byibgPr = myReader[4].ToString();
prod.sellPr = myReader[5].ToString();
prod.quantity = myReader[6].ToString();
tbxProductID.Text = prod.proid;
tbxName.Text =prod.prodname;
tbxModel.Text = prod.proMdl;
tbxserial.Text = prod.serialN;
tbxbyingprice.Text = prod.byibgPr;
tbxSellingprice.Text = prod.sellPr;
tbxQuantity.Text = prod.quantity;
prod.imgg = (byte[])(myReader[7] );
if (prod.imgg == null)
{
pBX.Image = null;
}
else
{
MemoryStream mstrm = new MemoryStream(prod.imgg);
Bitmap bmp = new Bitmap(mstrm);
}
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
com.Cancel();
con.Close();
}
Try to consult this question:
convert binary to bitmap using memory stream
Also, it might depend on DBType of the 8th column of the query.
I have a WPF application with various textboxes and a dropdown box. I am trying to update my SQLite db, with the details that are entered into them. I have re-worked the method before I used to insert the data into the SQLite db in the first place. The issue is when I execute the code I get an error “SQL Logic error or missing database near "(": syntax error.”
private void ButtonEditExmUpdate_OnClick(object sender, RoutedEventArgs e)
{
var ModifiedDateTime = DateTime.Now;
{
var ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (var DbConnection = new SQLiteConnection(ConnString))
{
try
{var InsertIntoTable = (#"Update [Exm]
Set(ExmID = #ExmID, ExmEnvironmentType = #ExmEnvironmentType, ExmURL = #ExmURL, ExmServer = #ExmServer, ExmModifiedDate = #ExmModifiedDate, ExmDeleted = #ExmDeleted)
WHERE(Exm.ExmDeleted = 0) AND (Exm.ExmID = '" + ExmID.Text + "')");
var insertIntoUsernamePasswordString = (#"Update [ExmUsernamePassword]
Set (ExmUsername = #ExmUsername, ExmPassword = #ExmPassword, ExmServer = #ExmServer, ExmModifiedDate = #ExmModifiedDate)
WHERE(ExmUsernamePassword.Deleted = 0) AND (ExmUsernamePassword.ExmUsernamePasswordsID = '" + ExmUsernamePasswordsID.Text + "')");
var insertIntoExmTable = new SQLiteCommand(insertIntoExmTableString);
var insertIntoExmUsernamePasswordTable = new SQLiteCommand(insertIntoUsernamePasswordString);
insertIntoExmTable.Connection = DbConnection;
insertIntoExmUsernamePasswordTable.Connection = DbConnection;
DbConnection.Open();
insertIntoExmTable.Parameters.AddWithValue("#ExmEnvironmentType", ComboBoxExmEnvironmentType.Text);
insertIntoExmTable.Parameters.AddWithValue("#ExmURL", TextBoxExmUrl.Text);
insertIntoExmTable.Parameters.AddWithValue("#ExmServer", TextBoxExmServerName.Text);
insertIntoExmTable.Parameters.AddWithValue("#ExmModifiedDate", ModifiedDateTime);
insertIntoExmUsernamePasswordTable.Parameters.AddWithValue("#ExmUsername", TextBoxExmUsername.Text);
insertIntoExmUsernamePasswordTable.Parameters.AddWithValue("#ExmPassword", TextBoxExmPassword.Text);
insertIntoExmUsernamePasswordTable.Parameters.AddWithValue("#ExmServer", TextBoxExmServerName.Text);
insertIntoExmUsernamePasswordTable.Parameters.AddWithValue("#ExmModifiedDate", ModifiedDateTime);
try
{
insertIntoExmTable.ExecuteNonQuery();
DbConnection.Close();
DbConnection.Open();
insertIntoExmUsernamePasswordTable.ExecuteNonQuery();
DbConnection.Close();
MessageBox.Show("Successfully updated");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
}
}
Error:
SQL Logic error or missing database near "(": syntax error.
I found what was causing the issue, this was because my SET statements were within brackets, so the final code looks like this for the SQL strings.
var InsertIntoTable = (#"Update [Exm]
Set ExmID = #ExmID, ExmEnvironmentType = #ExmEnvironmentType, ExmURL = #ExmURL, ExmServer = #ExmServer, ExmModifiedDate = #ExmModifiedDate, ExmDeleted = #ExmDeleted
WHERE(Exm.ExmDeleted = 0) AND (Exm.ExmID = '" + ExmID.Text + "')");
var insertIntoUsernamePasswordString = (#"Update [ExmUsernamePassword]
Set ExmUsername = #ExmUsername, ExmPassword = #ExmPassword, ExmServer = #ExmServer, ExmModifiedDate = #ExmModifiedDate
WHERE(ExmUsernamePassword.Deleted = 0) AND (ExmUsernamePassword.ExmUsernamePasswordsID = '" + ExmUsernamePasswordsID.Text + "')");
so I just want to view the values from my database to some textboxes in my project whenever the selected index of listbox changes
I have these code but whenever I click an item on my listbox, none of the textboxes displays a data or anything
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringHRMS"].ConnectionString);
conn.Open();
string selectone = "SELECT * FROM Applicant WHERE ApplicationNo = '" + ListBox1.SelectedValue.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectone, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
asln.Text = reader["LastName"].ToString();
asfn.Text = reader["FirstName"].ToString();
asmn.Text = reader["MiddleName"].ToString();
ashea.Text = reader["HEA"].ToString();
astitle.Text = reader["Title"].ToString();
aspos.Text = reader["Position"].ToString();
asaddress.Text = reader["Address"].ToString();
asbday.Text = reader["Birthday"].ToString();
asgender.Text = reader["Gender"].ToString();
asage.Text = reader["Age"].ToString();
asht.Text = reader["Height"].ToString();
aswt.Text = reader["Weight"].ToString();
asemail.Text = reader["Email"].ToString();
ascontact.Text = reader["ContactNumber"].ToString();
}
reader.Close();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
edit: Solved
I have a label that gets populated with a value from a database. If the user enters this value into a textbox below, I want to change the background. The label displays the value fine on screen, but when I try to match the values in the textbox's textchanged event, it shows as null.
public void button1_Click(object sender, RoutedEventArgs e)
{
txtAnswer.Clear();
txtAnswer.Background = Brushes.White;
int number = r.Next(3) + 1;
string queryEnglish = "SELECT englishVerb FROM verbTable WHERE (verbID = " + number + ")";
string queryFrench = "SELECT frenchVerb FROM verbTable WHERE (verbID = " + number + ")";
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\verbs.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand command = new SqlCommand(queryEnglish, con))
{
this.lblEnglishVerb.Content = (string)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryFrench, con))
{
this.lblFrenchVerb.Content = (string)command.ExecuteScalar();
}
}
}
public void txtAnswer_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtAnswer.Text == lblFrenchVerb.Content.ToString())
txtAnswer.Background = Brushes.LightGreen;
if (txtAnswer.Text == "test")
txtAnswer.Background = Brushes.AliceBlue;
}
Textchanged will probably get triggered the moment 'nothing' is placed into the Content. So on the first txtAnswer_TextChanged you might get nothing.