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();
}
Related
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();
}
This question already has answers here:
The multi-part identifier "TextBox1.Text" could not be bound in C# ASP.NET?
(3 answers)
Closed 9 years ago.
I know this is a duplicate to some questions here, but believe me I've tried all of them, and no luck.
I am new to C#+MySQL.
I have a database with 2 tables, programmers and softwares. I have a column in the softwares table named programmersid. It's one to many relation. I have two listboxes. The first one is with the programmers name, and when I click on a programmer, it's showing me the softwares that he has made.
When I click on a software, the text will be put into a textbox, and I have an update button. When I click it, it should update the name of that software.
Here is my code:
public partial class Form1 : Form
{
private DataSet ds;
private SqlConnection conn;
private SqlDataAdapter programmersadapter;
private SqlDataAdapter softwaresadapter;
protected string connectionString = "Data Source=ICEBOX19-PC\\ICEBOX;Initial Catalog=software;Integrated Security=True";
public Form1()
{
InitializeComponent();
conn = new SqlConnection(connectionString);
SqlCommand programmersselect = new SqlCommand("SELECT ID, Name FROM programmers", conn);
programmersadapter = new SqlDataAdapter(programmersselect);
SqlCommand softwaresselect = new SqlCommand("SELECT name FROM softwares WHERE programmerid = #ID", conn);
softwaresselect.Parameters.Add(new SqlParameter("#ID", SqlDbType.Int));
softwaresadapter = new SqlDataAdapter(softwaresselect);
showme();
}
private void showme()
{
ds = new DataSet();
conn.Open();
programmersadapter.Fill(ds, "programmers");
conn.Close();
listBox1.ValueMember = "id";
listBox1.DisplayMember = "name";
listBox1.DataSource = ds.Tables["programmers"];
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
command.ExecuteNonQuery();
conn.Close();
reload();
}
private void reload()
{
//listBox2.SelectedIndexChanged -= listBox2_SelectedIndexChanged;
softwaresadapter.SelectCommand.Parameters["#id"].Value = listBox1.SelectedValue;
var table = new DataTable();
softwaresadapter.Fill(table);
conn.Close();
listBox2.DisplayMember = "name";
listBox2.ValueMember = "id";
listBox2.DataSource = table;
//listBox2.SelectedIndexChanged += listBox2_SelectedIndexChanged;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
reload();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox2.Text;
textBox1.Text = textBox1.Text.Replace(" ", "");
}
}
I get this exception:
The multi-part identifier "System.Data.DataRowView" could not be bound.
It comes from the command.ExecuteNonQuery() in the button1.Click.
I've tried to change the :
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue, conn);
to
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
But I also get the same thing. Do you guys have some ideas ? I am looking for this since 2 hours now.
PS: I get the same error even if I try to delete
private void delete_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("delete from softwares where id="+listBox2.SelectedItem, conn);
command.ExecuteNonQuery();
conn.Close();
}
private void PopulateListBox(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
ls.Items.Add(row["id"]);
}
}
Then, calls
string value = ls.Items[0].ToString();
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();
}
}