Insert data from radio button into database - c#

Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.
How do I insert that data into the database based on what the user selects?

You can try this,
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into sample values(#payment)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#payment", payment.SelectedValue);
if (cn.State == ConnectionState.Closed)
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
lblmsg.Text = "Data entered successfully!!!";
}

I found the answer to my own question if someone needs it
try
{
var connection = getConnection();
connection.Open();
if (CashRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succsefully picked type");
}
else
{
MessageBox.Show("error");
}
}
else if (CardRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succesfully picked type");
}
else
{
MessageBox.Show("Error");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Luka,
Try it below.
Add HTML Markup like:
<asp:CheckBox ID="chkCash" runat="server" />
.cs file add below code.
string Cash = chkCash.Checked ? "Y" : "N";
And send or add value like.
SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(#Cash)"))
{
cmd.Parameters.AddWithValue("#Cash", Cash);
}

Related

Insert and Registration data not show in database table visual studio 2019

I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();

Trying to update data in C# does not work

I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.

Search Data from combobox and textbox. How to load data into datagridview after executenotquery()

Now I have a combobox i choose "Name" and input some text. I have query data from my database. but now i don't know how to load data into datagridview.
This is my code button Search:
private void btnSearch_Click(object sender, EventArgs e)
{
String strSearch = txtSearch.Text.Trim();
String Selected = cbSearch.GetItemText(cbSearch.SelectedItem);
switch (Selected)
{
case "All Search":
LoadData();
break;
case "Name":
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
MySqlCommand cmd = new MySqlCommand("Select * FROM sinhvien where name LIKE #name");
cmd.Connection = conn;
cmd.Connection.Open();
cmd.Parameters.Add(new MySqlParameter("#name", "%" + txtSearch.Text + "%"));
cmd.ExecuteNonQuery();***//I dont't know what to do after query here***
MessageBox.Show("Delete this row successfully!\n",
"Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (MySqlException)
{
MessageBox.Show("Error load data from database!","Notification", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
break;
break;
}
}
then how to load data from database into datagridview:
private void LoadData()
{
try
{
conn = new MySqlConnection(connString);
if (conn.State == ConnectionState.Open)
conn.Close();
daSinhVien = new MySqlDataAdapter("SELECT * FROM sinhvien", conn);
dtSinhVien = new DataTable();
dtSinhVien.Clear();
daSinhVien.Fill(dtSinhVien);
dgvSinhVien.DataSource = dtSinhVien;
}
catch (MySqlException)
{
MessageBox.Show("Can't not load data from sinhvien!!","Notification",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
cbSearch.Items.Add("All Search");
cbSearch.Items.Add("Name");
cbSearch.Items.Add("Age");
cbSearch.Items.Add("Class");
cbSearch.Items.Add("Address");
}
Why are you using cmd.ExecuteNonQuery();?
That's for executing statements that you don't expect to have data returning - like a command that adjusts some records.
Instead, you might be looking for something like:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
... this is off the MSDN page: https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx

C# update code for logout using mysql

im doing an update statement where the datetimepicker(logout) will insert into the same row as login but its making another row when i logout here is the link : http://imgur.com/a/rAWhi
ps. the problem here is the logout button is inserting into another row.. but i want to insert it in the same row.
here is my code :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from empinfo where username = '" + label4.Text + "' and IDNUMBER = '" + textBox1.Text + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Input your id number");
}
else if (i == 0)
{
MessageBox.Show("Username and IDNUMBER didn't match.", "Log-In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateuser();
login frmm = new login();
frmm.Show();
this.Close();
}
con.Close();
}
public void updateuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmdupdate;
cnn.Open();
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout = #logout";
cmdupdate.CommandText = "Insert into employee (logout) values (#logout)";
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
As #Ben in the comments pointed out, you do not need to use insert and only want update so change your code like this:
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout=#logout";
cmdupdate.CommandText += "WHERE IDNUMBER=#IDNUMBER";
cmdupdate.Parameters.AddWithValue("#IDNUMBER", textBox1.Text.Trim());
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
The Where is to make sure it only updates the IDNUMBER on the textbox.
I think you should create different methods for login and logout like
For LOGIN
public static long id;
public void loginuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into employee (logout) values (#logout)";
cmd.Parameters.AddWithValue("#login", DateTime.Now);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId; // it will return the id of last inserted row
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
For LOGOUT
public void logoutuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "update employee set logout = #logout WHERE IDNUMBER=#ID";
cmd.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}

Checking database data from textbox

I have a textbox which will take the input from user and search whether the inserted data is available in SQL database table or not. If the data is in table then it will update two column(time_out and day_out) of the same row.
Or else it will show an error message. This code below is not working. Please help.
try
{
SqlConnection con3 = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=db-ub;Integrated Security=True");
con3.Open();
SqlCommand cmd2 = new SqlCommand(#"SELECT Count(*) FROM Visitors WHERE Id=#id",con3);
cmd2.Parameters.AddWithValue("#id", textBox_VIex.Text);
SqlCommand cmd3 = new SqlCommand("UPDATE Visitors SET Day_Out=#dO,Time_Out=#tO WHERE Id=#id", con3);
cmd3.Parameters.AddWithValue("#id", 1);
cmd3.Parameters.AddWithValue("#dO", DateTime.Now);
cmd3.Parameters.AddWithValue("#tO", DateTime.Now);
int o = cmd3.ExecuteNonQuery();
MessageBox.Show("Good Bye!");
this.Close();
FormCheck f2 = new FormCheck();
f2.Show();
}
catch
{
MessageBox.Show("Error!");
textBox_VIex.Clear();
}
Please refer to my changes to your code,
int o = cmd3.ExecuteNonQuery();
Returns the count of number of rows affected by the Query. If it is zero it means that id was not in the database.
try
{
SqlConnection con3 = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=db-ub;Integrated Security=True");
con3.Open();
SqlCommand cmd2 = new SqlCommand(#"SELECT Count(*) FROM Visitors WHERE Id=#id",con3);
cmd2.Parameters.AddWithValue("#id", textBox_VIex.Text);
SqlCommand cmd3 = new SqlCommand("UPDATE Visitors SET Day_Out=#dO,Time_Out=#tO WHERE Id=#id", con3);
cmd3.Parameters.AddWithValue("#id", int.Parse(textBox_VIex.Text));
cmd3.Parameters.AddWithValue("#dO", DateTime.Now);
cmd3.Parameters.AddWithValue("#tO", DateTime.Now);
int o = cmd3.ExecuteNonQuery();
if(o > 0)
MessageBox.Show("Good Bye!");
else
MessageBox.Show("Error!");
this.Close();
FormCheck f2 = new FormCheck();
f2.Show();
}
catch
{
MessageBox.Show("Error!");
textBox_VIex.Clear();
}
Look into comments in code.
First, this is good way to deal with connection, etc
int? result = null; // note nullable int
try
{
Using (SqlConnection con = New SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=db-ub;Integrated Security=True"))
{
con.Open();
// You don't really care to check up front if the record with id=xx exists because
// if it doesn't, you get 0 records updated
// unless you do something with the result of that query
Using (SqlCommandcmd As New SqlCommand("UPDATE Visitors SET Day_Out=#dO,Time_Out=#tO WHERE Id=#id", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", 1); // <<-- Are you always passing "1"?????
cmd.Parameters.AddWithValue("#dO", DateTime.Now);
cmd.Parameters.AddWithValue("#tO", DateTime.Now);
result = cmd.ExecuteNonQuery();
}
con.Close()
}
}
catch
{
// optionally, log error or show error msg in second msgBox below. Save it to a variable here
}
// Separate query and result processing
// Check the result. If result is still null, your query failed. If not 0 - you updated your records
if (result != null && (int)result > 0)
{
MessageBox.Show("Updated record OK");
}
else
{
if (result == null)
{
MessageBox.Show("The construct failed"); // optionally add error msg here
}
else
{
MessageBox.Show("The record I was looking for is not in DB");
}
}
// I don't know what you do with your form logic
this.Close();

Categories

Resources