Well, I have a simple program that is writing to a Database. I am trying to add validation to the textbox like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length < -1)
{
MessageBox.Show("Don't Leave this field blank!");
}
}
catch
{
//todo
}
}
and My save to database code,
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
But still it is adding blank data to the database and strange thing is in the database I have not allowed null but still data is getting added. Any clues where I am wrong?
I don't see you stopping the database to add empty content. You are validating on the textbox_textchanged event which will only validate the text when someone enters the data. You need to put the validation on button1's click event like this:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("Null String !!!!!!!!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
//log
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
An empty textbox.Text has zero byte length , not -1.
To be sure the textbox is not empty you should apply the Trim() to the current text
Also there is no need to catch an exception on this code.
Moreover, don't use the TextChanged event to validate the text box.
There is the Validating event for this purpose. (Remember to set CauseValidation=True for the control)
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
e.Cancel = true;
}
}
of course you could move all the validation in the code where do you update the database
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
return;
}
using(SqlConnection con = new SqlConnection(
"Server=DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
{
SqlCommand sql1 = new SqlCommand("INSERT into Book " +
"VALUES(#text1, #text2,#dtValue", con);
sql1.Parameters.AddWithValue("#text1", textBox1.Text);
sql1.Parameters.AddWithValue("#text2", textBox2.Text);
sql1.Parameters.AddWithValue("#dtValue", dateTimePicker1.Value.ToShortDateString());
con.Open();
sql1.ExecuteNonQuery();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
}
Related
I have created a listview that includes my database, but everytime i press ''List It'', it repeats itself in lisview. Do you know how to solve it?
And I fill textboxes to submit informations, it isnt seen in listview.
There's the code for Submit;
private void button1_Click(object sender, EventArgs e)
{
keko.Open();
cmd = new MySqlCommand("Insert into calisanlist(Adı,Soyadı,Yevmiye) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')", keko);
cmd.ExecuteNonQuery();
keko.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
There's the code for List It;
private void verilerigoruntule()
{
keko.Open();
MySqlCommand cmd = new MySqlCommand("Select * from calisanlist", keko);
MySqlDataReader gr = cmd.ExecuteReader();
while(gr.Read())
{
ListViewItem ekle = new ListViewItem();
ekle.Text = gr["Adı"].ToString();
ekle.SubItems.Add(gr["Soyadı"].ToString());
ekle.SubItems.Add(gr["Yevmiye"].ToString());
ekle.SubItems.Add(gr["Gun"].ToString());
ekle.SubItems.Add(gr["Maaş"].ToString());
listView1.Items.Add(ekle);
}
keko.Close();
private void button2_Click(object sender, EventArgs e)
{
verilerigoruntule();
}
Okay so here's my code. Everything works and saves to the database.
Though, it only stores the current value that's displayed in the combobox.
I want it to store all 3 values, for each value has its own checkboxes.
How would I go about coding something that saves each of the 3 values and the corresponding checkboxes to the database(sql)?
Form
, Code
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.Text + "', '" + cboStateOperator.Text + "', '" + cboStateType.Text + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to use "combobox.SelectedItem" or "combobox.SelectedValue". If your combobox is filled with datasource you need to define "DisplayMember" and "ValueMember" for it.
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.SelectedItem+ "', '" + cboStateOperator.SelectedItem+ "', '" + cboStateType.SelectedItem+ "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to get the combo box items for each combo box as shown below and then save it.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder comboBox1Items = new StringBuilder();
foreach (var item in comboBox1.Items)
{
comboBox1Items.Append(item + " ");
}
string cb1Items = comboBox1Items.ToString();
}
what's wrong with my code?I just want to add data into access database but it show ExecuteNonQuery:
Connection property has not been initialized.
It's pretty weird because in other project code similar to this works just fine.
OleDbCommand command = new OleDbCommand();
OleDbConnection connect = new OleDbConnection();
OleDbDataReader reader;
public Absen()
{
InitializeComponent();
}
MainForm form_utama;
private void Absen_Load(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual Studio Project\Minor baru - back up\Minor baru\Absensi.accdb;Persist Security Info=False;";
}
private void button1_Click(object sender, EventArgs e)
{
if (idkaryawantxt.Text != "")
{
string q = "insert into tableAbsensi (ID,ID_divisi,Waktu,Tanggal) values ('" + idkaryawantxt.Text.ToString() + "','" + iddivisitxt.Text.ToString() + "','" + (DateTime.Now.ToString("hh:mm :")) + "','" + (DateTime.Now.ToString("MM-dd-yyyy")) + "')";
dosomething(q);
}
}
private void dosomething(String q)
{
try
{
connect.Open();
command.CommandText = q;
command.ExecuteNonQuery();
connect.Close();
}
catch (Exception e)
{
connect.Close();
MessageBox.Show(e.Message.ToString());
}
}
You didn't set your Command's Connection property
command.Connection = connect;
Before execute your command you should set it as the error said
I have a problem with the button3 it's the UPDATE BUTTON, The message box keeps saying it's a syntax error in the UPDATE Statement. And also if I create another listbox, if I insert a new data, it does not make me insert another data in the 2nd listbox. So if I insert something on the 1st listbox, that index would, for example, be 9, then I would try to insert on the next listbox, but then it would proceed to the index 10.
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != 1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1 (name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Problem 1: you are missing = Symbol while providing input parameters.
Try This:
string q = "update Table1 set [name]= '" + textBox2.Text.ToString() + "' where id= " + listBox1.SelectedItem.ToString();
Problem 2: you are not assigning connection object to `OleDbCommand.
Add This: before executing command
cmd.Connection=cn;
Complete Code:
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex!=-1)
textBox2.Text = l.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1(name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set [name] ='" + textBox2.Text.ToString() + "' where id =" + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.Connection=cn;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Suggestion : your query is open to SQL injection attacks , i would suggest to use Parameterised Queries to avoid them.
Using Parameterised Queries :
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = "update Table1 set [name]=#name where id=#id";
cmd.Parameters.AddWithValue("#name",textBox2.Text.ToString());
cmd.Parameters.AddWithValue("#id",listBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
In the above code (btn3) your are missing id =
Write code like this :
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id=" + listBox1.SelectedItem.ToString();
UPDATE :
My Access query function:
public void ExecuteAccessQurey(string _pQurey)
{
OleDbConnection con = new OleDbConnection("DatabaseConnectionString");
OleDbCommand cmd = new OleDbCommand(_pQurey, con);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
con.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
private void Display()
{
SqlDataReader reader;
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=Adama6DaY; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT " + " dbo.GMYAKU.NAME, " +"FROM " +
" dbo.GMYAKU " + " WHERE " +
" (dbo.GMYAKU.YKCODE = ('" + txtHidden.Text + "'))",con) ;
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
this.TextBox1.Text = reader["NAME"].ToString();
}
else
{
// 読めないので画面を初期化する
}
cmd.Connection.Close();
cmd.Dispose();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
connetionString = ("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=redacted; Integrated Security=True");
string strSQL ;
strSQL = "UPDATE GMYAKU SET";
strSQL += " NAME = '" + (TextBox1.Text) + "'";
strSQL += " WHERE";
strSQL += " YKCODE= '" + txtHidden.Text + "'";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(strSQL, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
// cnn.Close();
//MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
// MessageBox.Show("Can not open connection ! ");
}
Response.Redirect("Default.aspx");
}
It may be something as simple as not having the control in an update panel to refresh with the new data, but without more information/context it is impossible to tell
I think you need to check the Request.QueryString["YKcode"]; before assigning value to txthidden.text like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString["YKcode"].equals("") && Request.QueryString["YKcode"]!=null)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
}