C# WPF Mysql combobox duplicates values - c#

I have a form that has 2 comboboxes. The first combobox (cb_CharacterName) which contains the character/user name and is loaded when the form opens, this works fine.
When a name is choosen in the cb_CharacterName the other combobox (Talent_Name) checks the (cb_CharacterName) combobox for the name and loads the talents the character/user has, this is also works fine.
However when a new character/user has been choosen in the cb_CharacterName the Talent_Name combobox does not remove the talents from the previous character, and just adds more to the list. At the same time if i select the same character twice i get duplicates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
/// <summary>
/// Interaction logic for Character.xaml
/// </summary>
public partial class Character : Window
{
public Character()
{
InitializeComponent();
}
private void character_name_loader(object sender, RoutedEventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
string Query = "SELECT Name_ FROM dark_heresy.character_";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string charactername = myReader.GetString("Name_");
cb_CharacterName.Items.Add(charactername);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_CharacterName_DropDownClosed(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
string Query = "SELECT * FROM dark_heresy.character_ WHERE Name_='" + cb_CharacterName.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string career = myReader.GetString("Class");
string world = myReader.GetString("World_Type");
string strength = myReader.GetInt32("Str").ToString();
string weaponskill = myReader.GetInt32("WS").ToString();
string ballisticskill = myReader.GetInt32("BS").ToString();
string fellowship = myReader.GetInt32("Fel").ToString();
string perception = myReader.GetInt32("Per").ToString();
string intelligence = myReader.GetInt32("Int_").ToString();
string agility = myReader.GetInt32("Agi").ToString();
string willpower = myReader.GetInt32("WP").ToString();
string toughness = myReader.GetInt32("Tough").ToString();
TextCareer.Text = career;
TextWorld.Text = world;
TextStrength.Text = strength;
TextWeaponskill.Text = weaponskill;
TextBallisticskill.Text = ballisticskill;
TextFellowship.Text = fellowship;
TextPerception.Text = perception;
TextIntelligence.Text = intelligence;
TextAgility.Text = agility;
TextWillpower.Text = willpower;
TextToughness.Text = toughness;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_Talent_NameDropDownOpen(object sender, EventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
string Query = "SELECT Talent_Name FROM dark_heresy.learned_talents WHERE Character_Name='" + cb_CharacterName.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string talent_name = myReader.GetString("Talent_Name");
Talent_Name.Items.Add(talent_name);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_Talent_Name_DropDownClosed(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
string Query = "SElECT learned_talents.Talent_Name , talents.Description FROM dark_heresy.learned_talents, dark_heresy.talents WHERE learned_talents.Talent_Name = talents.TalentName AND learned_talents.Character_Name = '" + cb_CharacterName.Text + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string talents_description = myReader.GetString("Description");
Talents_Description.Text = talents_description;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
}
}
How can i make the Talent_Name combobox each time a new character/user or the samme has been choosen to flush the old informations and add the new ones in? i presume this would also remove the duplications problem.
Also, does WPF have a SelectedIndex? right now i am using DropdownClosed which is not the perfect choice, since when i use the arrows in the keyboard the values the character/user contains does not gets updated.

You want to call the Clear() method:
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
// You're missing this line!
Talent_Name.Items.Clear();
while (myReader.Read())
{
string talent_name = myReader.GetString("Talent_Name");
Talent_Name.Items.Add(talent_name);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
There should be a SelectedItem property you can use too grab the current item.

Related

How do i add textbox values to Access database?

I want to add textbox values to relevant columns in access database, the connection has been established but when i click the submit button the values are not added.
here is the code i tried, any help is appreciated
protected void Button1_Click(object sender, EventArgs e)
{
string EmailAddress = TextBox1.Text;
string UserName = TextBox2.Text;
string Password = TextBox3.Text;
try
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Bheki Ndhlovu\source\WebSites\WebSite8\App_Data\UserDatabase.accdb; Persist Security Info = False;");
OleDbCommand cmd = new OleDbCommand();
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)");
con.Open();
if (con.State == ConnectionState.Open)
{
TextBox1.Text = "sssss";
cmd.Parameters.Add("#EmailAddress", OleDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox3.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception error)
{
//Show error message as error.Message
}
}
Try adding connection string with OleDbCommand.
cmd = new OleDbCommand("INSERT INTO User(EmailAddress, UserName, Password) VALUES(#EmailAddress, #UserName, #Password)",con);
Here is an example were all data operations reside in a class. If the add new record is successful the new primary key is returned. On failure you can query the exception that raised the problem for failure.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace MS_AccessAddNewRecord_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addRecordButton_Click(object sender, EventArgs e)
{
var ops = new Operations();
var newId = 0;
if (ops.AddNewRow(companyTextBox.Text, contactNameTextBox.Text, contactTitleTextBox.Text, ref newId))
{
newIdentifierTextBox.Text = $"{newId}";
}
else
{
MessageBox.Show($"{ops.Exception.Message}");
}
}
}
/// <summary>
/// This class should be in a separate class file, I placed it here for easy of learning
/// </summary>
public class Operations
{
private OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder
{
Provider = "Microsoft.ACE.OLEDB.12.0",
DataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
};
private Exception mExceptiom;
public Exception Exception
{
get
{
return mExceptiom;
}
}
/// <summary>
/// Add a new record, upon success return the new primary key for the record in pIdentifier parameter
/// </summary>
/// <param name="pName"></param>
/// <param name="pContactName"></param>
/// <param name="pContactTitle"></param>
/// <param name="pIdentfier"></param>
/// <returns></returns>
public bool AddNewRow(string pName, string pContactName, string pContactTitle, ref int pIdentfier)
{
bool Success = true;
try
{
using (OleDbConnection cn = new OleDbConnection { ConnectionString = Builder.ConnectionString })
{
using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName, ContactTitle) " +
"Values(#CompanyName,#ContactName, #ContactTitle)";
cmd.Parameters.AddWithValue("#CompanyName", pName);
cmd.Parameters.AddWithValue("#ContactName", pContactName);
cmd.Parameters.AddWithValue("#ContactTitle", pContactTitle);
cn.Open();
int Affected = cmd.ExecuteNonQuery();
if (Affected == 1)
{
cmd.CommandText = "Select ##Identity";
pIdentfier = Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
}
catch (Exception ex)
{
Success = false;
mExceptiom = ex;
}
return Success;
}
}
}
Perhaps in the Page_Load method you do not have a if(!isPostback) and so the value of the TextBoxes are getting reset on a postback before the Button1_Click method is executed.
If EmptyWaterHole's answer is not the problem, is it erroring out on the connection?
Be sure 'VarChar' is the correct data type for each of the fields.
Also, be sure the values do not exceed the size (ie: if you set the field to only allow up to 25 characters and your value is over 25 characters, the value will not be added).
In addition, if you are not allowing nulls and one of the values exceeds the limit, the whole record will not be added.
Mr. Hungry. Try it like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
try this it will work if you are using access as your database
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO REPORT (patientName,tel,hostel,id no,department,diagnose,gender) values(#patientName,#tel,#hostel,#id no,#department,#diagnose,#gender)";
connection.Open();
command.Parameters.AddWithValue("#patientName", textBox1.Text);
command.Parameters.AddWithValue("#tel", textBox2.Text);
command.Parameters.AddWithValue("#hostel", textBox3.Text);
command.Parameters.AddWithValue("#id no", textBox4.Text);
command.Parameters.AddWithValue("#department", textBox5.Text);
command.Parameters.AddWithValue("#diagnose", richTextBox1.Text);
command.Parameters.AddWithValue("#gender", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Patient record Have been save successfully....");
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}

c# - MySQL to Array to MSSQL Query Statement

I'm working on a program to link two databases (MySQL and MSSQL) and show them in a datagrid table.
I'm getting a count to get the number of arrays value, then assigning the array, then using the array value to return into a datagrid table.
The problem I have is skuArray[RowCount++] = Convert.ToInt32(myReader[0]);is returning error: cannot convert int to string. I changed it to skuArray[RowCount++] = Convert.String(myReader[0]); and it complied correctly but gives the message Object reference not set to an instance of an object.
All SQL Queries have been tested and successfully execute.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Xml.Serialization;
using System.Data.SqlClient;
namespace SQL_Database_Connector
{
public partial class Sync_Databases : Form
{
string serverInfo; // MySQL Database Information
string portInfo;
string databaseInfo;
string usernameInfo;
string passwordInfo;
string MSserverInfo; // MSSQL Database Information
string MSdatabaseInfo;
string MSusernameInfo;
string MSpasswordInfo;
public string[] skuArray;
public string queryString;
public int RowCount;
public Sync_Databases()
{
InitializeComponent();
}
private void Sync_Databases_Load(object sender, EventArgs e)
{
if (File.Exists("data.xml")) // MySQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
serverInfo = info.server;
portInfo = info.port;
databaseInfo = info.database;
usernameInfo = info.username;
passwordInfo = info.password;
read.Close();
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT COUNT(*) " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
RowCount = myReader.GetInt32(0); // Get Row Count
//MessageBox.Show(RowCount.ToString()); // Test Row Count
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with Row Count: "+ ex.Message);
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT catalog_product_entity.sku AS 'SKU' " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
skuArray[RowCount++] = Convert.ToString(myReader[0]); // Assigning Array Values
//MessageBox.Show(skuArray.ToString()); //T est
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with MySQL query to capture Array: "+ ex.Message);
}
if (File.Exists("data2.xml")) // MSSQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data2.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
MSserverInfo = info.server;
MSdatabaseInfo = info.database;
MSusernameInfo = info.username;
MSpasswordInfo = info.password;
read.Close();
}
try
{
string connectionString = string.Format("Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3};", MSserverInfo, MSdatabaseInfo, MSusernameInfo, MSpasswordInfo);
string sql = string.Format("SELECT ItemLookupCode,Description, Quantity, Price, LastReceived " +
"FROM Item " +
"WHERE ItemLookupCode IS IN {0} " +
"ORDER BY LastReceived ASC;", skuArray);
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "sql_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "sql_table";
SqlConnection conn = new SqlConnection();
}
catch (Exception ex)
{
MessageBox.Show("Problem with SQL query or connection: "+ ex.Message);
}
}
}
}
Where have you initialised the array?
I dont see any line which would say:
skuArray = new string[RowCount];
RowCount is just a placeholder i am using.

Insert data in to access database with C#

For a program I'm making, I want to add the countrycode, the zipcode of the city and the name of the city in a table. If this information is already in the table, nothing needs to happen.
However, new records won't insert in my table.
For example: with only 'BE, '3580', 'Beringen' in my table. I start my program.
First I insert the values that are already in my table and nothing happends.
Second I try to add a new value (for example: ('BE' '3500', 'Hasselt')). I get the messagebox with: "Data added succesfully!".
After that, I try to add the same value as before ('BE' '3500', 'Hasselt'). My program does nothing.
But when I open Access, to take a look in the table. No new data was added.
What did I do wrong?
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = DeJongDatabase.mdb; Persist Security Info = True";
This is the rest of my code
static class Zipcodes
{
public static void checkAndSavePostCode(String country, String zipcode, string city)
{
Globals.connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = Globals.connection;
command.CommandText = string.Format("SELECT * FROM Zipcodes WHERE CountryCode = #countryCode AND City= #city AND Zipcode= #zipcode");
command.Parameters.AddWithValue("#countyCode", country);
command.Parameters.AddWithValue("#city", city);
command.Parameters.AddWithValue("#zipcode", zipcode);
OleDbDataReader postcodeReader = command.ExecuteReader();
bool exists = false;
while (postcodeReader.Read())
{
exists = true;
}
postcodeReader.Close();
command.Dispose();
Globals.connection.Close();
OleDbCommand writeCommand = new OleDbCommand();
writeCommand.Connection = Globals.connection;
try
{
Globals.connection.Open();
if (!exists)
{
if (Globals.connection.State == System.Data.ConnectionState.Open)
{
/*writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(#countryCode, #zipcode, #city)";
writeCommand.Parameters.AddWithValue("#countyCode", country);
writeCommand.Parameters.AddWithValue("#city", city);
writeCommand.Parameters.AddWithValue("#zipcode", zipcode); */
writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(?, ?, ?)";
writeCommand.Parameters.Add(new OleDbParameter("#countryCode", OleDbType.VarChar)).Value = country;
writeCommand.Parameters.Add(new OleDbParameter("#zipcode", OleDbType.VarChar)).Value = zipcode;
writeCommand.Parameters.Add(new OleDbParameter("#city", OleDbType.VarChar)).Value = city;
if (writeCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("Data saved successfuly...!");
}
}
else
{
MessageBox.Show("FAILED");
}
}
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Source);
MessageBox.Show(ex.ToString());
}
finally
{
Globals.connection.Close();
}
This works fine for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}

Inserting time and date using Datetimepicker

I'm building an application with C# code.
This is a simple code for inserting values unto the database. I have successfully inserted the values but when I checked on the time column where I have used the datetimepicker, it would only show 0000-00-00 00:00:00. So my problem is, How can you insert time and date only into the database?
private void button1_Click(object sender, EventArgs e)
{
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
timeanddate.Format = DateTimePickerFormat.Custom;
timeanddate.CustomFormat = "MM dd yyyy hh mm ss"; timeanddate.Value.ToShortDateString();
string Query = "Insert into fillupform.fillupform (filename,instructor,time,score) values('" + this.filename.Text + "','" + this.instructor.Text + "','" + this.timeanddate.Text + "','" + this.score.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
no need to use a MySqlDataReader
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
string Query = "INSERT INTO fillupform.fillupform (filename,instructor,time,score) VALUES (#filename,#instructor,#time, #score);";
using (MySqlConnection conDataBase = new MySqlConnection(constring))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase))
{
cmdDatabase.CommandType = CommandType.Text;
cmdDatabase.Parameters.AddWithValue("#filename", this.filename.Text);
cmdDatabase.Parameters.AddWithValue("#instructor", this.instructor.Text);
cmdDatabase.Parameters.AddWithValue("#time", this.timeanddate.Text);
cmdDatabase.Parameters.AddWithValue("#score", this.score.Text);
try
{
cmdDatabase.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Connect to two tables

I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}

Categories