I am updating some data in SQL server database and then showing that data into a list box. It is updating the data but shows the duplicate entries(old and new both) unless I restart the windows form. Anyone know how to refresh it on a button click event?
neither refresh nor update funttions are working
private void button2_Click(object sender, EventArgs e)
{
SqlDataReader dr;
try
{
SqlCommand cmd = new SqlCommand("select prod, eng from comp", cn);
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
listBox1.Items.Add((String)dr["prod"] + "\t\t" + (string)dr["eng"]);
}
cn.Close();
listBox1.Refresh();
}
If you want to redraw the listbox, try this:
listBox1.Invalidate();
This will redraw your control.
Try:
listBox1.Items.Clear();
before writing the db read items, if you only want the new items to show in the listbox, like this:
private void button2_Click(object sender, EventArgs e)
{
SqlDataReader dr;
try
{
SqlCommand cmd = new SqlCommand("select prod, eng from comp", cn);
cn.Open();
dr = cmd.ExecuteReader();
listBox1.Items.Clear();
while (dr.Read())
{
listBox1.Items.Add((String)dr["prod"] + "\t\t" + (string)dr["eng"]);
}
cn.Close();
listBox1.Invalidate();
}
Related
So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("select * from worker where number='" + textBox1.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
hello guys can you help me with this
i need the MessageBox to show this message if No record is found but i don't know how to include the IF with the code
and a max numbers or letters for textbox1 is 10 if the user put more then the MessageBox (max10) will appear
You can use SqlDataReader.HasRows property to determine whether any records were returned. like:
if (dr.HasRows)
{
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
But couple of other things to add:
Use SqlParamaters instead of concatenation queries, you are open to SQL Injection.
Not really sure how would you accomplish showing more than one record in TextBox controls you probably need a Grid or add your returned rows/recrods to a List<T> or List<Worker> where Worker class can have properties for columns.
Use using statement with SqlCommand/SqlConnection and SqlDataReader as they implement IDisposable
this dr[0].ToString() could potentially throw Null Reference Exception, research and see how you can safeguard it.
So your code more or less should look like:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
using (SqlCommand cmd = new SqlCommand("select * from worker where number=#Number", con))
{
cmd.Parameters.AddWithValue("#Number", textBox1.Text);//or explicity specify type using .Add
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
//Add to List<Worker> with properties Name and Number etc
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
}
I am designing a web form to insert data into sql database.I just want to check that email id which is unique already exists or not.
code:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox2.Text))
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("select shop_email from shop where shop_email=#email", con);
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Label1.Text = "email id already exists";
}
con.Close();
}
}
I tried above code but its not working i.e Label is not displaying anything.Any help will be thankful.
Problem : You are writing your code in TextBox_TextChanged Event handler so it would be invoked for everytime whenever there is a change in the TextBox and it would not give you the result untill unless you enter the complete Email-ID.
Solution 1: You need to write the above code in some Button Click Event handler as below:
protected void btnSearch_Click(object sender,EventArgs e)
{
//Write your code here
}
Solution 2: if you want to keep your code in the TextBox TextChanged Event handler but still want to identify the EmailID you can use LIKE operator instead of = operator
Try This:
SqlCommand cmd = new SqlCommand("select shop_email from shop
where shop_email LIKE #email", con);
cmd.Parameters.AddWithValue("#email", "'%"+TextBox2.Text +"%'"+);
try to add else statement in case if user/email does not exist
Also move this code to button click event or some other event. On Text Box text change event it will not return result.
using (var con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True"))
using(var cmd = new SqlCommand("select 1 from shop where UserID=#UserID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserID", TextBox2.Text);
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
Label1.Text = "userid already exists";
}
else
{
Label1.Text = "userid doesn't exists";
//Create new user
}
}
}
My Combobox contains the name of a waiter.
When I allot the table to the selected waiter its status become true but the combobox item doesn't change.
programming on page_load:---
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
coding on save button for waiter status= true on allot button:
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
}
Problem is after you change the database you haven't refresh or reload the combobox databinding.
I would re factor your code as below and call the load data method after database update.
private void frmTableAllotment_Load(object sender, EventArgs e)
{
dtTmPkr.Value = System.DateTime.Now;
LoadComboBox();
}
private void btnAllocate_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update waiterentry2 set status='true' where name=#name", con);
cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);
cmd.ExecuteNonQuery();
con.Close();
LoadComboBox();
}
private void LoadComboBox()
{
while(cmbWaiter.Items.Count >0)
cmbWaiter.Items.RemoveAt(0);
cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbWaiter.Items.Add(dr["name"]);
}
dr.Close();
cmd = null;
con.Close();
}
Try to call he code which you have written in form load after successful db operation in btnAllocate_Click event
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();