How do I link textboxes?
Scenario:
TextBox_Supplier
TextBox_Address
TextBox_Supplier is autocomplete and it's working. When typing is done in TextBox_Supplier, the TextBox_Address will select supplier's address.
My code does not work:
private void txb_vendor_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txb_address.Text))
{
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon.getcon();
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name = {0}",txb_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
address = txb_address.Text;
}
PurCon.con.Close();
}
}
Thank you for helping me!
instead of
address = txb_address.Text;
write
txb_address.Text = address;
Try to use Parameterized Query instead of concatenation of the strings.
Do Change as #Mohit suggested and also wrap the supplier name with single quotes, since supplier name is string type and in sql String should be wrap in single Quotes other wise this will give SQL Error
"SELECT address FROM tbl_Supplier WHERE supplier_name = '{0}'"
----^
I already solved this problem last week. And I'm so angry to myself!
The textbox_Address does not changed once, it stacks up when the textbox_Supplier_TextChaged. So I put Clear() method to clear previous input address.
public void AddressTbxLoad()
{
DBCon PurCon = new DBCon();
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon2.con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name LIKE '{0}%'", cbx_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
txb_address.Text = address;
}
PurCon.con.Close();
}
private void cbx_vendor_SelectedIndexChanged(object sender, EventArgs e)
{
txb_address.Clear();
AddressTbxLoad();
}
private void Purchase_Load(object sender, EventArgs e)
{
VendorTbxLoad();
}
Related
I'm new at coding and I need help for a school project.
I want to update a database using MySQL but I can't find out how to get the update working.
I have googled a bit but I haven't been able to find a solution so I figured I'd ask the question on this site.
I have successfully made a connection to the database and show the contents in a data grid. The connection has a name: "conn". If anyone knows a way on how I can get the update to work I'd be happy to hear from you!
This is my XAML.CS code:
public void Click_btnBewerk(object sender, RoutedEventArgs e)
{
string vzitter2 = txtVZitter.Text;
string info2 = txtInfo.Text;
string zetels2 = txtZetels.Text;
string stroming2 = txtStroming.Text;
string partij = cmPartijen.Text;
conn.Updateinfo();
}
This is my DBconn code:
public DataView Updateinfo()
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "UPDATE partijen SET fvzitter='vzitter2', info='info2', zetels='zetels2', stroming='stroming2' WHERE partij='partij'";
MySqlDataReader reader = command.ExecuteReader();
DataTable dtData = new DataTable();
dtData.Load(reader);
conn.Close();
return dtData.DefaultView;
}
you are doing a Reading action on the db instead an update.
Just replace your code with this
public void Updateinfo()
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "UPDATE partijen SET fvzitter='vzitter2', info='info2', zetels='zetels2', stroming='stroming2' WHERE partij='partij'";
command.ExecuteNonQuery();
conn.Close();
}
if you want pass the variables to the updateinfo method just do it
private void Updateinfo(string fvzitter, string info, string zetels, string stroming, string partij)
{
string query = "UPDATE partijen SET fvzitter=#fvzitter, info=#info, zetels=#zetels, stroming=#stroming WHERE partij=#partij"
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = query;
command.Parameters.AddWithValue("#fvzitter", fvzitter);
command.Parameters.AddWithValue("#info", info);
command.Parameters.AddWithValue("#zetels", zetels);
command.Parameters.AddWithValue("#stroming", stroming);
command.Parameters.AddWithValue("#partij", partij);
command.ExecuteNonQuery();
conn.Close();
}
My output on SQL query is not viewing on my textbox, when the form load it must be automatically inserted to my textbox. The only output on my textbox is System.Data.SqlClient.SqlCommand
I don't know whats wrong or missing on my codes. Please help me, sorry I'm just a newbie on c#
Any type of response is greatly appreciated. Thank you in advance.
private void EmailGen_Load(object sender, EventArgs e)
{
connect.Open();
string emailto = "select emailaddress from emails where password = ''";
string emailfr = "select emailaddress from emails where password != null";
SqlCommand emailt = new SqlCommand(emailto, connect);
SqlCommand emailf = new SqlCommand(emailfr, connect);
emailt.ExecuteNonQuery();
txBEmailRec.Text = emailt.ToString();
txBEmailFr.Text = emailf.ToString(); ;
connect.Close();
// TODO: This line of code loads data into the 'kwemDataSet.tblProducts' table. You can move, or remove it, as needed.
this.tblProductsTableAdapter.Fill(this.kwemDataSet.tblProducts);
}
You should use ExecuteScalar(); instead of ExecuteNonQuery(); And also, you code seems to missing to execute emailf SqlCommand.
You could see this reference as well.
private void EmailGen_Load(object sender, EventArgs e)
{
connect.Open();
string emailto = "select emailaddress from emails where password = ''";
string emailfr = "select emailaddress from emails where password != null";
SqlCommand emailt = new SqlCommand(emailto, connect);
SqlCommand emailf = new SqlCommand(emailfr, connect);
txBEmailRec.Text = emailt.ExecuteScalar().ToString();
txBEmailFr.Text = emailf.ExecuteScalar().ToString();
connect.Close();
// TODO: This line of code loads data into the 'kwemDataSet.tblProducts' table. You can move, or remove it, as needed.
this.tblProductsTableAdapter.Fill(this.kwemDataSet.tblProducts);
}
Hi im trying to insert data into my DataBase. The program runs but it never save the values!!.
heres the code:
using System.Data.SqlClient;
namespace Database_1._0
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"DataSource=LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Luis\documents\visual studio 2015\Projects\Database_1._0\Database_1._0\DB.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DateTime dateTime = DateTime.UtcNow.Date;
string user = "1614258779876465426";
string pass = "3Cp5CeXrfghdfght";
string frecuencyCode = "ANNUAL";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void logo_Click(object sender, EventArgs e)
{
MessageBox.Show("Database_1._0 \nWritten by: Luis", "About");
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
using (SieteWS SieteWS = new SieteWS())
{
Respuesta respuesta = SieteWS.SearchSeries(user, pass, frecuencyCode);
foreach (internetSeriesInfo seriesInfo in respuesta.SeriesInfos)
{
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
}
and the Error says:
errorCS0103: The name 'CommandText' does not exist in the current context. And when I use a watch I found out this: cmd.CommandText =""; . Can somebody tell me what im doing wrong please.?
So first of all. move cn.Close(); outside of the loops. If it's not the cause for your problem now, it will cause a problem later.
If that doesn't fix your problem look further.
It's just a poke in the dark given the information I have, but try running following code sets (inside foreach loop) and see if any of them work:
set 1:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES ('"+seriesInfo.seriesId+"', '"+seriesInfo.spanishTitle+"'
, '"+seriesInfo.frequency+"')", cn);
cmd.ExecuteNonQuery();
set 2:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES (#SerieID, #SerieName, #SerieFrecuency)", cn);
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
Let me know how it works out
Try this...
Modify the line below to include the name of the database. So that it will read [Your database Name].[dbo].[Serie]
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
Your default database may not be the one that has your "Serie" table in it.
I am trying to create login operation.
How can I use another column's data by using a username and password query to my db.
In my db, there is a another column(personnel_type_id) and I want to create a session with username and password but also the personnel_type_id data.
How can I use personel_type_id data without using another parameter in my code?
protected void btnGiris_Click(object sender, EventArgs e)
{
string sorgu = "Select * from Personnels where VS_personnel_username = #kullaniciAdi AND VS_personnel_password= #sifre ";
SqlCommand cmd = new SqlCommand(sorgu, cnn);
cmd.Parameters.AddWithValue("#kullaniciAdi", txtKullaniciAdi.Text);
cmd.Parameters.AddWithValue("#sifre", txtSifre.Text);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session.Timeout = 300;
Session.Add("kullaniciAdi", dr["VS_personnel_username"].ToString());
Response.Redirect(Request.RawUrl);
}
else
{
lblSonuc.Text = "Kullanıcı girişi sağlanamadı";
}
cnn.Close();
}
Should be something like:
protected void btnGiris_Click(object sender, EventArgs e)
{
string sorgu = "Select * from Personnels where VS_personnel_username = #kullaniciAdi AND VS_personnel_password= #sifre ";
SqlCommand cmd = new SqlCommand(sorgu, cnn);
cmd.Parameters.AddWithValue("#kullaniciAdi", txtKullaniciAdi.Text);
cmd.Parameters.AddWithValue("#sifre", txtSifre.Text);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session.Timeout = 300;
Session.Add("kullaniciAdi", dr["VS_personnel_username"].ToString());
Session.Add("your_user_id_parameter", dr["personnel_type_id"].ToString());
Response.Redirect(Request.RawUrl);
}
else
{
lblSonuc.Text = "Kullanıcı girişi sağlanamadı";
}
cnn.Close();
}
If you don't want/can/need to store that "personnel_type_id" as a session variable you have to implement some kind of lookup in the database each time you need it.
I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}