How do I refresh combobox item after selecting one item? - c#

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

Related

C# program reports "Index was outside the bounds of the array"

May I ask, how can I get error for this? It is so confusing. I get bug like this and I try to fix, but it does not work at all. I'm just a beginner.
namespace WindowsFormsApp1
{
public partial class Schedule : Form
{
public Schedule()
{
InitializeComponent();
}
MySqlConnection con = new MySqlConnection(#"Data Source=localhost;port=3306;Initial Catalog=Payroll;User Id=root;password=''");
MySqlDataReader dr;
int tc = 0;
private void Schedule_Load(object sender, EventArgs e)
{
datagrid();
fillsched();
}
public void datagrid()
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter("Select * from employee where Pstatus='Active'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
public void fillsched()
{
con.Open();
MySqlDataReader dr;
MySqlCommand cmd = new MySqlCommand("select * from updateschedule ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
int data = dr.GetInt32("empSched");
comboBox1.Items.Add(data);
}
con.Close();
}
public void getsched()
{
if (Int32.TryParse(comboBox1.SelectedItem.ToString(), out tc))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from updateschedule where empSched=#empSched ", con);
cmd.Parameters.Add("#empSched", MySqlDbType.Int32).Value = tc;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["TimeIn"].ToString();
textBox3.Text = dr["TimeOut"].ToString();
label5.Text = tc.ToString();//to pass the data in the combobox1
}
con.Close();
}
}
public void view()
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
getsched();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
view();
}
}
private void button1_Click(object sender, EventArgs e)
{
insert();
insertempsched();
}
public void insert()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule (empSchedID,empID,empIN,empOut)VALUES(#empSchedID,#empID,#empIn,#EmpOut)", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.Date).Value = textBox2.Text;
cmd.Parameters.Add("#empOut", MySqlDbType.VarChar).Value = textBox3.Text;
execnonquery(cmd, "Data Inserted");
}
public void insertempsched()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update employee set empSched=empSched where empID=#empID", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
public void execnonquery(MySqlCommand sqc, string mymsg)
{
con.Open();
if (sqc.ExecuteNonQuery() == 1)
{
MessageBox.Show(mymsg);
}
else
{
MessageBox.Show("Query not Executed");
}
con.Close();
}
}
}
"Index was outside the bounds of the array" in c# always indicates that you are trying to get values based on column index number or row index number from datagrid or datatables or arrays and column or row does not exist at that position or index.
I think you are getting error at following line which exists in "view" method.
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Also to catch the errors it's a good practice to use try catch blocks in all the methods.
You can modify your method like this
public void view()
{
try
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Move to next Row in dataGridView

I am trying to develop a form which will search the database for the entered name. save the selected row and then move to the next one. but when i search again it clears the previously saved row.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(datatable);
DV.RowFilter = string.Format("proName LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = DV;
}
private void Form1_Load(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand("select * FROM productDetails",connection);
DataSet dataset = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Zimad\Desktop\project1.accdb";
connection.Open();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(datatable);
dataGridView1.DataSource = datatable;
connection.Close();
nRow = dataGridView1.CurrentCell.RowIndex;
}
private void button1_Click(object sender, EventArgs e)
{
if (nRow < dataGridView1.RowCount)
{
dataGridView1.Rows[nRow].Selected = false;
dataGridView1.Rows[++nRow].Selected = true;
}
}
button1 is used to save the selected row.
#Fabio is right. What i did here is that i loaded the search results in a textbox and later loaded the information against the item in the dataGridView
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.Visible = true;
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
listBox1.Items.Clear();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
listBox1.Items.Add(reader["proName"].ToString());
}
}
connection.Close();
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
dataGridView1.Rows.Add();
dataGridView1[0, 0].Value = reader["proName"].ToString();
}
}
connection.Close();
}

Updating list view items

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();
}

need help for using selected item from listview as a variable on sql query

think there is a problem at
cmd.Parameters.AddWithValue("#name", listView1.SelectedItems );
anybody have idea for that??
private void Form_Load(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(tools.ConnectionString);
SqlCommand cmd = new SqlCommand("select * from Employees",cnn);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
ListViewItem lvi = new ListViewItem();
lvi.Text = dr["FirstName"].ToString();
lvi.SubItems.Add(dr["LastName"].ToString());
listView1.Items.Add(lvi);
}
cnn.Close();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(tools.ConnectionString);
SqlCommand cmd = new SqlCommand("select EmployeeId,BirthDate from Employees where FirstName = #name ",cnn);
cmd.Parameters.AddWithValue("#name", listView1.SelectedItems );
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
MessageBox.Show("Id= "+dr["EmployeeID"].ToString() + "\nBirth Date= "+dr["BirthDate"].ToString());
}
cnn.Close();
}
thanks
This is what you need to change.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
{
SqlConnection cnn = new SqlConnection(tools.ConnectionString);
SqlCommand cmd = new SqlCommand("select EmployeeId,BirthDate from Employees where FirstName = #name ",cnn);
cmd.Parameters.AddWithValue("#name", listView1.SelectedItems[0].Text );
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
MessageBox.Show("Id= "+dr["EmployeeID"].ToString() + "\nBirth Date= "+dr["BirthDate"].ToString());
}
cnn.Close();
}
}
I would imagine selected items is a collection, try the selected item from the collection.

The multi-part identifier "System.Data.DataRowView" could not be bound #2 [duplicate]

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();

Categories