I am new to C# and i am trying to insert some values to my database i created inside visual studio.
-I am creating a recipe application-
So in the form i have some components such as text boxes(For title,ingredients,description), a dropdown item(combobox) to specify if it's food or sweet and a button to insert all these data into my database.
When i am pressing the button i can add everything(all the text boxes) to the database except the dropdown value.
Here is the code inside the button_click
private void addItemButton_Click(object sender, EventArgs e)
{
string dat = "Insert into [Table](Title,Category,Ingredients,Description) Values('" + titleTextBox.Text + "','" + dropdownCategory.SelectedValue + "','" + addIngredientTextBox.Text + "','" + addDescriptionTextBox.Text + "')";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
I make a code example, which can insert the combobox value to the database successfully.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string dat = string.Format("Insert into [Sample](Title,Category,Ingredients,Description)values('{0}','{1}','{2}','{3}')", textBox1.Text, comboBox1.SelectedItem,textBox2.Text,textBox3.Text);
string connectionString = #"connectionstring";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("success");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.AddRange(new object[] { "basketball","football", "volleyball" });
}
}
I would try to look into content of string dat.
It might contain invalid data if "dropdownCategory.SelectedValue" returns something
that you don't expect.
Other than that, order of Open(), ExecuteNonQuery() and Close() methods might be incorrect. Try to read docs of these methods.
Another thing that you should look into is error message that is returned(if there is one). They are usually pretty informative.
Ok i don't know if it's correct or not but it worked on me.
I changed
dropdownCategory.SelectedValue
to
dropdownCategory.Text
and it worked.
Related
I'm learning C# for a small project with an Access DB.
I get no error when I click on the button to run my sql statement through OleDbCommand but no row is inserted in the table though.
I think my connection is perfectly set up because I get an error if I don't use the right type for a column (e.g. insert a string in an int).
I know the button is working too because I add an action on a text which is working. Finally I know also that my query works since I have tried it directly via VS on my table.
Am I missing a step?
Here my code:
namespace ProjetFalk
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btn_onclick_Click_1(object sender, EventArgs e)
{
label12.Text = string.Empty;
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=DBFalk.accdb";
OleDbConnection dbconn = new OleDbConnection(connectionString);
dbconn.Open();
string dbcommand = "INSERT INTO Produit (NOM,REFERENCE) VALUES('TEST2', 'test2')"; // + TextBox_Nom.Text + "')";
OleDbCommand cmd = new OleDbCommand(dbcommand, dbconn);
cmd.ExecuteNonQuery();
dbconn.Close();
}
}
}
Please be tolerant, it's new for me. (I have read the docs on Microsoft too for my setup)
I'll start off by saying that I'm pretty inept at coding (have yet to learn how to utilize classes and how they work in depth), and that I've never worked with sql before doing this project.
The idea here is that you connect to an sql database, after which a datagridview element gets filled with data from a table called TABLE_1 by default. The user should then be able to input, delete and save data.
The first two work operations work perfectly, but the saving is the problem. I've banged my head against a wall for about 4 days trying to get the saving to work, but I just cant get it to do so. The saving is done with the method Button3_click.
Any insight as to what I should do?
Is the main chunk of the code where you connect the part where I'm
messing up?
//initialize the classes I guess, on some youtube guides they did so
SqlConnection con;
DataSet ds;
SqlDataAdapter a;
DataTable t;
SqlCommandBuilder scb;
static string tablename = "TABLE_1";
string constring;
//connect button
private void button1_Click(object sender, EventArgs e)
{
try
{
//connect using info from textboxes, connection is ok
constring = "server=" + Server.Text + ";database=" + DB.Text + ";UID=" + UID.Text + ";password=" + Password.Text;
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
Save.Enabled = true;
//check if table name is empty, if so default to TABLE_1
if (textBox1.Text != "")
{
tablename = textBox1.Text;
}
else
{
tablename = "TABLE_1";
}
a = new SqlDataAdapter("SELECT * FROM " + tablename, con);
DataTable t = new DataTable();
a.Fill(t);
datagrid.DataSource = t;
//
label5.Text = Server.Text;
con.Close();
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
//save button
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
DataTable t = new DataTable();
a.TableMappings.Add(tablename, "t");
scb = new SqlCommandBuilder(a);
a.Update(t);
con.Close();
}
Use the following example which sets up the adapter, dataset and table name as private variables.
Also, I recommend to never use one letter variable names as a) it's difficult to debug b) when getting into more lines of code it's going to be difficult to know what a variable is for.
Next up, using SELECT *, it' unknown if you have setup a auto-incrementing primary key which is needed to perform updates. In the example below, Id is auto-incrementing.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsDataAdapterExample
{
public partial class Form1 : Form
{
private SqlDataAdapter _companiesSqlDataAdapter;
private DataSet _companiesDataSet;
private string _tableName = "Companies";
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
_companiesDataSet = new DataSet();
_companiesSqlDataAdapter = new SqlDataAdapter(
"SELECT Id, FirstName, LastName, PhoneNumber, City FROM dbo.Companies;",
"Data Source=.\\sqlexpress;Initial Catalog=ForumExample;" +
"Integrated Security=True");
var builder = new SqlCommandBuilder(_companiesSqlDataAdapter);
_companiesSqlDataAdapter.Fill(_companiesDataSet, _tableName);
dataGridView1.DataSource = _companiesDataSet.Tables[_tableName];
}
private void SaveButton_Click(object sender, EventArgs e)
{
_companiesSqlDataAdapter.Update(_companiesDataSet, _tableName);
}
}
}
I'm trying to develop a web site that receives data from SQL server, then show info on listbox and textbox, and when user select an option then insert data to a table in the database.
My ASP.NET controls are:
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
I need the data loaded to a listbox, but not sure how to do directly. To retrieve the info and see if its working I did this:
protected void Page_Load(object sender, EventArgs e){
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView2.DataSource= reader;
GridView2.DataBind();
con.Close();
var nProject = GridView2.Rows.Count;
for (int b = 0; b < nProject ; b++)
{
ListBox1.Items.Add(GridView2.Rows[b].Cells[0].Text);
}
}
Then I tried to set the selected info to a textbox, but nothing happens (because I managed to insert data from textbox to a SQL Server INSERT) :
protected void ListBox1_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox2.Text = ListBox1.SelectedValue;
Response.Write("ListBox selectedIndexChanged");
}
The info is send back to the database with a button click:
protected void btnInsert_Click(object sender, EventArgs e)
{
var IP = "111.111.11";
txtStatus.Text = "Start";
txtProject.Text = "PR-02";
var indice = 0;
// This always returns "0"
if (ListBox1.SelectedItem != null)
{
indice = ListBox1.SelectedIndex;
}
txtProject.Text = indice.ToString();
// Sql INSERT works fine, but only with info manually created. I can't get the real info to work
SqlConnection con = new SqlConnection("****");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[table3]
([project]
,[user_task]
,[status]
,[ip]
,[location])
VALUES
('" + txtProject.Text + "', '" + txtUser.Text + "', '" + txtStatus.Text + "', '" + txtIP.Text + "', '" + txtLocation.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The Page_Load is one of the first events to run every time there is a call to the server, this means that it runs before the btnInsert_Click event.
This means that you are repopulating the ListBox1 before checking the SelectedItem, this is why it always returns "0"
You have to consider this and use something like
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
It is hard to understand what you want to do, but I think the ListBox1_OnSelectedIndexChanged is useless if you correct the Page_Load event.
Side notes:
You should really start by putting using statements where you can (on SqlConnection and SqlCommand)
Watch out for Sql Injections, may be a simple test program, but you should NEVER, EVER do this: #"INSERT INTO (...) VALUES ('" + txtProject.Text + "'"
use parameters instead:
using(SqlConnection con = new SqlConnection("****"))
using(SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table3] ([project]) values (#project)", con))
{
cmd.Parameters.AddWithValue("#project", txtProject.Text);
}
It seems you are using .Net Framework with aspx pages, you should really consider using newer technologies (.net core).
I'm done designing my project software that passes information in my software textbox to my local mysql xampp database.
im have this error message
Please help with the code below. What am i getting wrong from the code below?
I have two textboxes namely "seed" and "password" and button "encrypt" and "decrypt"
namespace seed
{
public partial class CryptSeed : Form
{
public CryptSeed()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("server=localhost;user id=seedcrypt;persistsecurityinfo=True;database=seed;");
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
string query = "INSERT INTO info ('id','seed','password','ip') VALUES (NULL,'"+seed.Text+ "','" +password.Text+ "',NULL)";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("INSERTED SUCCESSFULLY !!! ");
}
}
}
If you are connecting to mysql database you got it all wrong.First you need mysqlconnector for c#.
Second what exactly are you trying to do?save?read?
public partial class CryptSeed : Form
{
public CryptSeed()
{
InitializeComponent();
}
//you will need to specify the port Mysql uses:3306
private void Form1_Load(object sender, EventArgs e)
{
// If you are saving data you cant do it here.
// But still will show you how to do it in a button //click
//event.
}
private void button1_Click(object sender,EventArgs e)
{MySqlConnection con = new MySqlConnection("server=localhost;port=3306; username=seedcrypt;database=seed;password=xxxxxxx");
string query = "INSERT INTO
info('id','seed','password','ip') VALUES
(NULL,'"+seed.Text+ "','" +password.Text+ "',NULL)";
con.Open();
MysqlCommand cmd = new
MysqlCommand(query,con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("INSERTED SUCCESSFULLY !!!
");
}
}
}
I asked this same question on SO-pt but no one seemed to understand the question, though I made it clear.
I have a form that I'll use to
Register customers in the database.
Alter any of the registers.
Show the registers.
Here I'm instantiating this form:
private void mnuRegister_Click(object sender, EventArgs e)
{
var frmRegister = new frmRegisterScreen();
frmRegister.Show();
}
As you can see, I'm calling the form from within a ToolStripMenuItem called mnuRegister.
Now, there are a number of properties from this form that I'm customizing at the Load` event, that'll make it more specific for registering the customers.
Below is the code:
private void frmRegisterScreen_Load(object sender, EventArgs e)
{
//set the database connection and the Sql command to be used
string conString = "Server = .\\sqlexpress; trusted_connection = yes; database=he_dados;";
SqlConnection con = new SqlConnection(conString);
string sel = "SET DATEFORMAT dmy;\n" //set date format to dd//mm/yyyy
+ "Insert into Customer(" +
"Name,IDCard,Phone,Address,Observation)" +
"values(" +
"'" + txtName.Text +
"','" + mskIDCard.Text +
"','" + mskPhone.Text +
"','" + txtAddress.Text +
"','" + txtObs.Text + "');";
SqlCommand selCmd = new SqlCommand(sel, con);
//set the form properties relate to the customer registration
lblMain.Text = "Register Customer";
tsbSave.Text = "Save Changes";
}
As you can see, this code is obviously intended to insert data in a table.
Now, what I want to do is to call another instance of this form:
private void mnuViewRegister_Click(object sender, EventArgs e)
{
var frmViewRegister = new frmRegisterScreen();
frmViewRegister.Show();
}
Then I want to set specific properties, required for me to make a simple query using the same form, for example:
private void frmRegisterScreen_Load(object sender, EventArgs e)
{
//set the database connection and the Sql command to be used
string conString = "Server = .\\sqlexpress; trusted_connection = yes; database=he_dados;";
SqlConnection con = new SqlConnection(conString);
string sel = "Select * from Customer;";
SqlCommand selCmd = new SqlCommand(sel, con);
//set the form properties relate to the customer registration
lblMain.Text = "View Customer Registers";
tsbSave.Text = "View";
}
In other words, I would like to have event calls specific to the instance of the form, instead of having one event that's valid for any of the instances.
Is that possible?
If you find yourself configurating a great deal of UI elements, then just create separate Forms. It's not like they cost you anything, and they'll be easier to maintain. But it looks like you're only changing a couple of UI elements (like the label), so that's not too bad.
Either move the configuration logic into two separate methods on the Form, like ConfigureForRegistration and ConfigureForViewingRegistration, and then call the appropriate one when you instantiate the Form:
var frmRegister = new frmRegisterScreen();
frmRegister.ConfigureForRegistration();
frmRegister.Show();
Or you could create an enumeration for each possible view, and pass a value in when you instantiate the Form:
public enum ScreenOption
{
Register,
AlterRegister,
ViewRegister
}
public class frmRegisterScreen
{
public frmRegisterScreen(ScreenOption option)
{
switch (option)
{
case ScreenOption.ViewRegister:
//set the database connection and the Sql command to be used
string conString = "Server = .\\sqlexpress; trusted_connection = yes; database=he_dados;";
SqlConnection con = new SqlConnection(conString);
break;
...
}
}
}
var frmRegister = new frmRegisterScreen(ScreenOption.ViewRegister);
frmRegister.Show();