Refreshing the combobox after inserting data in mysql c# - c#

Hello so i want to refresh my combobox after i add or delete data from it now if i add data it doesnt get refreshed i have to rerun the program to see the changes but i want to get it refresh in the time i add the data..
the code when i add data:
private void button5_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO filmi.film (film) VALUES ('" + this.tB_Dodaj.Text + "')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("You added a new movie!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Movie couldnt be added!!\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
and with each insert the data gets displayed in the combobox but only when i rerun the program
this is how i fill combobox:
void Fillcombo()
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "SELECT * FROM filmi.film ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

i have to rerun the program to see the changes but i want to get it
refresh in the time i add the data..
I suspect that you are calling the Fillcombo() method in Form_Load event handler.
if you want to update the combobox for every insert and delete operations in your table you need to call Fillcombo() immediatly after executing the command.
Try This:
int status = dataCommand.ExecuteNonQuery();
transakcija.Commit();
if(status > 0)
{
Fillcombo();
MessageBox.Show("You added a new movie!");
}
in your FillCombo clear the items before adding the new items to remove the duplicates.
comboBox1.Items.Clear(); //add this statetement before adding items
comboBox2.Items.Clear(); //add this statetement before adding items
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}

ADO.NET object works in a disconnected state, so, adding a record to your datatable doesn't automatically shows up in your combo. You need to call again FillCombo, (clearing the items already in combos, going again to the database to retrieve every record again, adding them to your comboboxes) or just simply adding the film to your already filled combos as a single item
Also pay attention to Sql Injection (use always a parameterized query)
private void button5_Click(object sender, EventArgs e)
{
string conString = "datasource=localhost;port=3306;username=root;password=";
string cmdText = "Insert INTO filmi.film (film) VALUES (#film)";
using(MySqlConnection dataConnection = new MySqlConnection(conString))
using(MySqlCommand dataCommand = new MySqlCommand(cmdText, dataConnection))
{
try
{
dataConnection.Open();
dataCommand.Parameters.AddWithValue("#film", this.tB_Dodaj.Text);
// If ExecuteNonQuery returns a value > 0 then your record has been inserted
// Just add the name of the film to the two combos
if(dataCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("You added a new movie!");
comboBox1.Items.Add(this.tB_Dodaj.Text);
comboBox2.Items.Add(this.tB_Dodaj.Text);
}
}
catch(Exception ex)
{
MessageBox.Show("Fail to add a new movie! " + ex.Message);
}
}
}
As a last note, watch carefully your fillcombo method. You don't close and dispose the connection.

Related

Page_Load() load data don't go away

I am working on a visual web part that does simple CRUD operations and I have this strange behavior in Page_load().
I grab first record from query and assign some text fields when page is loaded. When I clear the form and update the form with new different inputs, those text fields remember the first values and ignores newly entered data.
Am I missing anything in Page_load() when I display data when the page is loaded?
public partial class VisualWebPart1UserControl : UserControl
{
string connstr = AdminDashBoard.Utility.GetConnectionString();
private DataSet sqlDst = new DataSet();
private static int RowNo = 0;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
string strQuery = "xxxxxxxxxxxxxxxxxxxxxx";
try
{
conn.Open();
SqlCommand sqlCmd = new SqlCommand(strQuery, conn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd);
sqlAdap.Fill(sqlDst);
//these fields remember first assigned data!!!
this.TextBox1.Text = sqlDst.Tables[0].Rows[RowNo][0].ToString();
this.TextBox2.Text = sqlDst.Tables[0].Rows[RowNo][1].ToString();
this.TextBox3.Text = sqlDst.Tables[0].Rows[RowNo][2].ToString();
this.DateTimeControl1.SelectedDate = Convert.ToDateTime(sqlDst.Tables[0].Rows[RowNo][3].ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
conn.Dispose();
}
}
thanks in advance

My combobox doesn't show data from database

my combo box needs to show data from my database but it shows empty.
here you have my code that i'm working on, visual studio dont show any error, but combobox shows empty, any tips ?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
try
{
cn.Open();
string query = "select * from fornecedor where nomefornecedor='" + comboBox1 + "'";
SqlCommand createCommand = new SqlCommand(query, cn);
SqlDataReader dr = createCommand.ExecuteReader();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteReader will return a reader which you then have to use to read back your results row by row, and populate your combo box accordingly.
For example, if you have a (non nullable) string column named "MyItem" in your fornecedor table, you would write something like this:
using (SqlDataReader dr = createCommand.ExecuteReader())
{
int myItemOrdinal = dr.GetOrdinal("MyItem");
List<object> comboBoxRows = new List<object>();
while (dr.Read())
{
string myItem = dr.GetString(myItemOrdinal);
comboBoxRows.Add(myItem);
}
}
comboBox1.BeginInvoke(() => comboBox1.Items.AddRange(comboBoxRows.ToArray()));
The last row populates the combo box on the UI thread, assuming reading the rows from the database is done on another thread (which is something you'd want to do to keep your UI responsive).

C# Mysql multiple queries

Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.

Delete record from MDF database

I want to create simple application in C#. It should be windowsForms app, with service-based database added to project. In this I want to make table (ID, name, second name) and in program show name into listBox. Current name selected in listBox will be deleted (row will be deleted)
Can anyone help me how to do it? I have try with dataset, this is working, but after I close app and run it again, table is full with data again.
For saving records into database and loading them in a listbox you can see..
save-data-to-database-then-load-data-to-listbox
Now,for deleting a record from a listbox you can code like this..
protected void removeButton_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem.Text == null)
{
MessageBox.Show("Please select an item for deletion.");
}
else
{
for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Selected)
{
DeleteRecord(ListBox1.Items[i].Value.ToString());
}
}
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
}
}
For deleting that record also from database use like this..
private void DeleteRecord(string ID)
{
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");
string sqlStatement = "DELETE FROM Table1 WHERE Id = #Id";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Id", ID);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Deletion Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}

How to delete from database selected item in ListView in C#

I am using Microsoft SQL Server and Visual Studio-C# 2010 Ultimate.
I have a ListView and some items in it. I want to delete an item when I selected it and I clicked the button but I could not write the SqlCommandtext and I could not find the select event for ListView.
Deleting selected data from database using listview c#
private void btnlvdeleterow_Click(object sender, EventArgs e)
{
foreach (int i in Listview2.SelectedIndices)
{
string test = Listview2.Items[i].Text;
Listview2.Items.Remove(Listview2.Items[i]);
SQLiteCommand conn = new SQLiteCommand();
conn.Connection = DbClass1.GetConnection();
string del = "delete from UserData where UserName='" + test + "'";
int result=dbclass1.ExecuteAndReturn(del);
}
}
There is a SelectedIndex property available with the ListView. When you click the button, pass this index and then your Sql query will be something like
delete from Products where ProductID = 'obj.ID' where obj is obtained from listView.SelectedIndex
protected void listview1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
//This retrieves the selected row
ListViewItem item= listview1.Items [e.ItemIndex];
// Fetch the control for ProductId using findControl
int productId=int.Parse((item.Findcontrol("ProductID") as TextBox).Text);
//then use this column value in your sqlcommand
using( SqlCommand cmd = new SqlCommand
("delete from Products where ProductID=#ProductId", connection ))
{
command.Parameters.Add(new SqlParameter("ProductId", productId));
//Then execute the query
}
}
try
{
for (int j = 0; j <= listView2.Items.Count - 1; j++)
{
string test = listView2.SelectedItems[j].SubItems[1].Text;
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=root";
string Query = "delete from TABLE_NAME where COL_NAME='" + test + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
MyConn2.Close();
MessageBox.Show("Data Deleted");
// txtCustomerName.Text = test;
//listView2.Items.Remove(listView2.Items[i]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Event you are looking for should be ListView.ItemSelectionChanged
where the eventArgs contains the selected Items

Categories