i have three text boxes for telephone number mobile number and for age;
i enter the details there and insert them in to the database. after insert how can i make textboxes cleared. it won't allow me to do so coz insert method is like this
public void insert(int mobile,int telephone,int age)
{
try
{
MySqlConnection asp= new MySqlConnection(conString);
asp.Open();
string insertString = "insert into users(mob,tele,age) values('"+mobile+"','"+telephone+"','"+age+"')
MySqlCommand cmd = new MySqlCommand(insertString,asp);
dr = cmd.ExecuteReader();
MessageBox.Show("New user added succesfully","Information");
//afteer this how to empty the three textboxes
// ihave used these three as integers in database
}
calling method is
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text))
You can use TextBox.Clear() method to clear the contents of the TextBox after the Insert()statement
Try This:
insert(int.parse(textbox1.Text),int.parse(textbox2.Text),int.parse(textbox3.Text));
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
After Calling Insert method Just use this
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text));
textBox1.Text =String.Empty;
textBox2.Text =String.Empty;
textBox3.Text =String.Empty;
(or)
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text));
textBox1.Text ="";
textBox2.Text ="";
textBox3.Text ="";
Related
I am currently working on WinForms application where on form I have one textbox for searching , and one ListView control where will be populated data from database as result of user's entry.
Here is the following code for implementation of TextChanged event on textbox control
private void tbSearchGlassOnShell_TextChanged(object sender, EventArgs e)
{
Form1 form = new Form1();
string cmdString = string.Empty;
try
{
string connString = string.Format("Server={0};Username={1};Database={2};Port={3};Password={4};",
form.Tbhostname, form.Tbusername, form.Tbdatabase, form.Tbport, form.Tbpassword);
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
cmdString = "SELECT shell_glass.shell_glass_id,shell.shell_name,glass.glass_name," +
"shell_glass.shell_glass_quantity,shell_glass.shell_glass_ordernumber," +
"shell_glass.shell_glass_datetime,shell_glass.user_id FROM shell_glass " +
"JOIN shell using (shell_id) JOIN glass using (glass_id)" +
"WHERE LOWER(glass.glass_name) LIKE '%" + tbSearchGlassOnShell.Text.ToLower() + "%'";
MySqlCommand command = new MySqlCommand(cmdString, conn);
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
ListViewItem item = new ListViewItem(reader["shell_glass_id"].ToString());
item.SubItems.Add(reader["shell_name"].ToString());
item.SubItems.Add(reader["glass_name"].ToString());
item.SubItems.Add(reader["shell_glass_quantity"].ToString());
item.SubItems.Add(reader["shell_glass_ordernumber"].ToString());
item.SubItems.Add(reader["shell_glass_datetime"].ToString());
item.SubItems.Add(reader["user_id"].ToString());
lvSearchGlassOnShell.Items.Add(item);
}
reader.Close();
}
catch (MySqlException ex)
{
form.TbSetupLog.AppendText("MySqlExepction: " + ex.Message + Environment.NewLine);
}
catch (Exception ex)
{
form.TbSetupLog.AppendText("Exception: " + ex.Message + Environment.NewLine);
}
}
For some reason, ListView control is displaying same value multiple times after user's entry as you can see on picture below
Question: how can I achieve that I have only one value but not duplicate after user's entry ?
The TextChanged event will be called for each character typed in the TextBox, so while you type the first letter a search is performed, then another one when you type the second letter and so on. You never clear the ListView items collection, so each search add another entry in the listview.
To solve your immediate problem just call
lvSearchGlassOnShell.Items.Clear();
before entering the reader loop.
But there are other problems in the code above. The serious one is the Sql Injection made possible because you concatenate strings to build the sql command.
Instead you need to use parameters in this way
try
{
lvSearchGlassOnShell.Items.Clear();
string connString = string.Format("Server={0};Username={1};Database={2};Port={3};Password={4};",
form.Tbhostname, form.Tbusername, form.Tbdatabase, form.Tbport, form.Tbpassword);
string cmdString = #"SELECT shell_glass.shell_glass_id,
shell.shell_name,glass.glass_name,
shell_glass.shell_glass_quantity,
shell_glass.shell_glass_ordernumber,
shell_glass.shell_glass_datetime,
shell_glass.user_id
FROM shell_glass
JOIN shell using (shell_id)
JOIN glass using (glass_id)
WHERE LOWER(glass.glass_name) LIKE #name";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand command = new MySqlCommand(cmdString, conn))
{
conn.Open();
command.Parameters.Add("#name", MySqlDbType.Text).Value = tbSearchGlassOnShell.Text;
MySqlDataReader reader = command.ExecuteReader();
....
}
}
catch(Exception ex)
....
Here I have remove the concatenation of the input text and placed a parameter placeholder to avoid the SqlInjection problem. Also note how the connection being a disposable object needs to be enclosed in a using statement to correctly clean the resources used by that object
I have some problems with spaces, i don't know how to solve it. It should be like this:
But it's actually like this:
public void azurirajPodatke()
{
richTextBox1.Clear();
try
{
con.Open();
string kom = "select * from Pecaros order by PecarosID asc";
cmd = new SqlCommand(kom, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
string id = dr[0].ToString();
string ime = dr[1].ToString();
string prezime = dr[2].ToString();
string adresa = dr[3].ToString();
string telefon = dr[4].ToString();
string grad = dr[5].ToString();
string linija = string.Format(
"{0,-15}|{1,-10}|{2,-15}|{3,-15}|{4,30}|{5,-15}",
id, ime, prezime, adresa, telefon, grad);
richTextBox1.Text += linija+"\n";
}
dr.Close();
}
}
First, you need to wrap all of the objects (textbox, labels, and etc) inside a groupBox object as shown in my image. This will allow you to configure padding and margins to control the distance your objects are away from another. Then, change the formBorderStyle to "FixedSingle" I would change the "MaximizeBox" to false. Then, change the textbox to a ListView or DataGrid. Finally, when you adjust the form size, it will rearrange the objects how you want them.
I am trying to create a Windows Form App using C# and SQL Server 2012.
My app has two text-boxes, a button and three group-boxes each having three check-boxes. I want the app to be getting the values of check-boxes that are checked, and saving all data to one row in SQL Server.
Example:
ID int PK not null,
Customer_Name varchar(50)
Item_Name nvarchar(max) null
Item_Model nvarchar(max) null
Item_Color nvarchar(max) null
I have created 3 Group boxes to the form each having 3 check boxes:
GroupBox1:
CheckBox1 - name : chkboxLaptop
CheckBox2 - name : chkboxDesktop
CheckBox1 - name : chkboxMonitor
GroupBox2:
CheckBox1 - name : chkboxDell
CheckBox2 - name : chkboxHp
CheckBox1 - name : chkboxLenovo
GroupBox3:
CheckBox1 - name : chkboxSilver
CheckBox2 - name : chkboxGrey
CheckBox1 - name : chkboxBlack
I want the Demo_Table table to look like this:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop Lenovo Black
Here is my Code:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
StringBuilder name = new StringBuilder();
foreach (Control ctrl in this.groupBox1.Controls)
{
if (ctrl is CheckBox)
{
if (((CheckBox)ctrl).Checked == true)
{
name.Append(((CheckBox)ctrl).Text.ToString() + " ");
con.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO Demo_Table (ID,Customer_Name,Item_Name) VALUES ( '" + txtBoxID.Text.ToString() + "','" + txtBoxName.Text.ToString() + "','" + ((CheckBox)ctrl).Text.ToString() + "')", con);
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
}
}
}
The App is giving me these results:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop NULL NULL
How do I add data in the Item_Model and Item_Color columns?
Your Assistance will be greatly appreciated.
(as xxbbcc said, never concatenate command text and always use parameters)
To achieve this, you can do something like this (comments in code)
Bear in mind that this code assumes that only one checkbox per group is selected and it will get first selected checkbox text. It would be better to use RadioButtons instead of CheckBoxes.
private void btnAdd_Click(object sender, EventArgs e)
{
//find all checkbox controls in group, get selected one and get its text.
string name = groupBox1.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string model = groupBox2.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string color = groupBox3.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
//connection
SqlConnection con = new SqlConnection(conString);
//command text (WITH PARAMETERS!)
string cmdText =
#"
INSERT INTO Demo_Table
(ID,Customer_Name,Item_Name, item_model, item_color)
VALUES
(#id, #customer_name, #item_name, #item_model, #item_color)
";
SqlCommand cmd = new SqlCommand(cmdText, con);
//add params
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = txtBoxID.Text;
cmd.Parameters.Add("#customer_name", SqlDbType.VarChar).Value = txtBoxName.Text;
cmd.Parameters.Add("#item_name", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#item_model", SqlDbType.VarChar).Value = model;
cmd.Parameters.Add("#item_color", SqlDbType.VarChar).Value = color;
//execute query
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
if you have additional questions, feel free to ask.
Here is basically what i want to do:
i have a web form in asp.net that has a first name and last name and a submit button,
now on submit button click, i would like to display an auto generated voucher code!
how should i go abut it?
this is what i have in my .cs file:
namespace WebApplication1
{
public partial class DetailsForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}``
[WebMethod]
public static string InsertMethod(string firstname, string lastname)
{
SqlConnection con = new SqlConnection(#"Data Source=KIMBERLY\SQLSERVER02;Initial Catalog=Chalegh;User ID=***;Password=***");
SqlCommand cmd = new SqlCommand("insert into TestTable values('"+ firstname +"','" + lastname +"')", con);
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
public static string GenerateVoucher(int length)
{
char[] CharArr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string randomString = string.Empty;
Random objRandom = new Random();
return randomString;
}
}
}
You need to do several things:
I will create a quick list, (I am assuming that you're using Visual Studio)
1) Create a button to submit button your changes (Drag a button onto the webpage)
2) Create an event handler for your button (Double click on your button)
3) Write the code for your handler
Create an entry in the database
Generate a voucher number
Display it back to the screen
You're pretty close for your database portion, like the comments suggest you want to use parameters instead.
using (var con =new SqlConnection(yourConnectionString))
{
SqlCommand cmd = new SqlCommand("insert into TestTable values('#firstName', '#lastName')", con);
SqlParameter paramFirstName= new SqlParameter();
paramFirstName.ParameterName = "#firstName";
paramFirstName.Value = firstName;
SqlParameter paramLastName= new SqlParameter();
paramLastName.ParameterName = "#lastName";
paramLastName.Value = lastName;
cmd.Parameters.Add(paramFirstName);
cmd.Parameters.Add(paramLastName);
con.Open();
cmd.ExecuteNonQuery();
}
For the generate the voucher number, I like Sudhakar Tillapudi's answer
String randomString = Guid.NewGuid().ToString("N").Substring(0, 6);
Then you need to display it to the screen.
Create a label on your webform (EG: lblVoucherNumber)
Assign the text value to the label
lblVoucherNumber.Text = randomString;
Please note that currently you aren't saving the voucher number. You'll likely want to save that voucher number somewhere (like in your TestTable, please rename this when you put it into production)
you can use GUID.NewGuid() to get the unique ID values.
Try This:
String randomString = Guid.NewGuid().ToString("N");
Suggestion 1: your INSERT INTO statement is open to sql injection attacks so i would suggest you to use Parameterised Queries to avoid them.
Suggestion 2: you need to identify the execution status of the ExecuteNonQuery() method by checking its return value. ExecuteNonQuery() returns total number of rows updated in the database.
Try This:
using(SqlConnection con = new SqlConnection(#"Data Source=KIMBERLY\SQLSERVER02;Initial Catalog=Chalegh;User ID=***;Password=***"))
{
using(SqlCommand cmd = new SqlCommand("insert into TestTable values(#firstname,#lastname)", con))
{
con.Open();
int status = cmd.ExecuteNonQuery();
if(status>0)
return "True";
return "False";
}
}
I have controls like TextBox, DropDownList and button on page.
When I enter data to TextBox, DropDown and if I click on button then it should add to GridView cell's TextBox and DropDownList respectively.
Example, When I enter the data to text box and hit the save button, I need to show it to GridView.
No data from DB.
May i know how to do it? Any Example code for reference ? Kindly advise, thank you
Put another button to insert data into database and write below code on click event.
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection cn = new SqlConnection("Your Connection strig");
string sql = "insert into tbl1 (column1,column2,column3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.ExecuteNonQuery();
}
Thanks