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.
Related
i wanna do a combobox for the classes , when i insert the type of class in it i want to selecteditem the row that was selected exmple: i chose second row then i insert to the database a 2
sql = "insert into etudiant (Nom, prenom, sexe,classess) " +
"values(#Nom, #prenom, #sexe,#classess)"/*+"class (nom_class)" + "values(#nom_class) "*/;
cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#nom", bunifuMaterialTextbox1.Text);
cmd.Parameters.AddWithValue("#prenom", bunifuMaterialTextbox2.Text);
cmd.Parameters.AddWithValue("#sexe", bunifuMaterialTextbox3.Text);
int id = comboBox1.SelectedIndex + 1;
cmd.Parameters.AddWithValue("#classess",Int32.Parse(comboBox1.SelectedItem.ToString()));//*/
//cmd.Parameters.AddWithValue("Num", bunifuMaterialTextbox6.Text);
//cmd.Parameters.AddWithValue("Classess", bunifuMaterialTextbox7.Text);
int result = cmd.ExecuteNonQuery();
i couldn't find a way to do it like that
i wanna find a way so i can insert to table classes int for the number of that row like the ID
For your question, you would like to achieve the current combobox selected index and insert
it into your database.
First, I want to mention that you should use comboBox1.SelectedIndex instead of comboBox1.SelectedItem.
Second, I use sqlconnection to complete the same operation, so you can modify the following code to apply to your code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = #"";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string sql = "insert into Example(Nom,Prenom,Sexe,Classess) values(#Nom,#Prenom,#Sexe,#Classess)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#Nom", textBox1.Text);
command.Parameters.AddWithValue("#Prenom", textBox2.Text);
command.Parameters.AddWithValue("#Sexe", textBox3.Text);
command.Parameters.AddWithValue("#Classess", comboBox1.SelectedIndex+1);
command.ExecuteNonQuery();
MessageBox.Show("add value successfully");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("class1");
comboBox1.Items.Add("class2");
comboBox1.Items.Add("class3");
comboBox1.Items.Add("class4");
}
}
I have an form that looks like that.Whenever I insert the Name and Age into the database and i press Show,it shows me all the entries(including the ones I just entered) but in the dbo.Table it does not update,everytime I try to refresh it gives me an error like this
I created the data base using Add->New Item->Service Base DataBase
This is the code for Inserting data:
private void button1_Click(object sender, EventArgs e)
{
string sql = "Insert into Elevi(Name,Age) values(#Name,#Age)";
command = new SqlCommand(sql, myConnection);
try
{
command.Parameters.AddWithValue("#Name", textBox1.Text);
command.Parameters.AddWithValue("#Age", Convert.ToInt32(textBox2.Text));
command.ExecuteNonQuery();
}
catch(Exception a)
{
MessageBox.Show(a.Message);
}
}
This is the code for Showing the data:
private void button2_Click(object sender, EventArgs e)
{
string sql;
try
{
sql = "Select * from Elevi";
command = new SqlCommand(sql, myConnection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
int IdCitit = Int32.Parse(dataReader.GetValue(0).ToString());
string NumeCitit = dataReader.GetValue(1).ToString();
int VarstaCitita = Int32.Parse(dataReader.GetValue(2).ToString());
MessageBox.Show($"Nume : {NumeCitit} \n Varsa : {VarstaCitita} \n Id: {IdCitit}");
}
}
catch (Exception Exceptie)
{
MessageBox.Show(Exceptie.Message);
}
}
For example, if I have the following input and i Press the button for printing the data it will work just fine
,but after I close the form and check the dbo.Elevi[Data] the new input will not be inserted there
The connection string is : #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TestareDataBase.mdf;Integrated Security=True"
I got it from Project->Add new DataSource
I think you code is not wrong, it seams like it is a database error. Perhaps the database file was created with a newer version of SQL Server Express than the one installed on your machine? Your SQL tools in VS are not compatible with the SQL server. Check the versions of the SQL tools.
Usually it happens when transaction doesn't get committed and it remains in memory, thus if we check the values by using same connection then we find latest one but when we try to verify it from table by using other connection we don't find it unless program commits the transaction.
try this:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(myConnection))
{
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = connection.BeginTransaction("MyTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = $"Insert into Elevi(Name,Age) values({textBox1.Text},{textBox2.Text})";
command.ExecuteNonQuery();
transaction.Commit();
}
catch(Exception a)
{
MessageBox.Show(a.Message);
}
}
}
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();
}
I just started with Visual Studio and I was wondering on how could I echo out the first row under the maincategory_name column of my maincategory table to the textbox1. I followed a guide on how to insert data through the database but what I wanted to know is how could I print out one so I'm kinda confused how will I be able to do it as for know, the output I get on my textbox is: System.Data.SqlClient.SqlCommand
namespace TrialForDatabase
{
public partial class Form1 : Form
{
SqlConnection sc = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename='C:\\Users\\flex\\Documents\\Visual Studio 2015\\Projects\\Inventory\\Inventory\\inventory.mdf';Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
textBox1.Text = cmd.ToString();
sc.Close();
}
}
}
This function first creates your SQL command, the executes it using SqlCommand.ExecuteReader(), then checks if you got any results using SqlDataReader.Read(), then displays the first column of the first row of your result to the Textbox:
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
using (var reader = cmd.ExecuteReader()){
if ( reader.Read() )
{
textBox1.Text = reader.GetString(0);
}
};
sc.Close();
}
See here for some more info on the classes used:
https://msdn.microsoft.com/de-de/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
ToString() more often that not is not redefined from Object, so it only prints the class's name.
What you want to do is print the result of your SQL command, and to do so, you will need... well, to execute it.
SqlCommand.ExecuteReader() will return a SQLDataReader object, from which you can read rows like you would with a simple array.
So if you really only want the first row, you could get away with a quick and dirty:
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
textBox1.Text = cmd.ExecuteReader()[0];
sc.Close();
}
I have question about my problem. Thru manustrip in form1 i have made new form2 when i click on a right option. This form is for deleting data in access database if you pick in combobox ID of row it deletes the whole row wher is ID 4 or somethig else... My combobox is connected on my database.
my code:
public partial class Form2 : Form
{
public string myConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bojan\Desktop\Programiranje\School\Novo\Novo\Ure.accdb"; // to je provider za Access 2007 in več - če ga ni na lokalni mašini ga je treba namestiti!!!
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.Ure' table. You can move, or remove it, as needed.
this.ureTableAdapter.Fill(this.dataSet1.Ure);
}
private void Brisanje_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = null;
myConnection = new OleDbConnection(); // kreiranje konekcije
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OleDbCommand cmd = myConnection.CreateCommand();
cmd.Connection = myConnection;
cmd.CommandText = "DELETE FROM Ure WHERE (ID) = '"+Izbor.SelectedValue+"'";
cmd.ExecuteNonQuery();
cmd.Prepare();
myConnection.Close();
}
}
Thanks for your help
As #musefan pointed out, you should really be using parameterised queries, the other issue seems to be the single quotes around ID which will result in a data type mismatch error. Finally, your connection and command objects implement IDisposable so I would recommend wrapping them in a using block.
The following code should work
using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
var idParam = new OleDbParameter("#id", Izbor.SelectedValue);
myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = #id";
myCommand.Parameters.Add(idParam);
myConnection.Open();
myCommand.ExecuteNonQuery();
}