private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConnectionString)
{
connection.Open();
SqlCommand cmd = new SqlCommand("update dictionary set word=#word", connection);
cmd.Parameters.AddWithValue("#word", wordTextBox.Text);
cmd.ExecuteNonQuery();
this.Close();
}
}
I created a way to take a selected value in a listbox and add the item to a text box on a seperate form. There I am attempting to give the user a way to change that word and have it reflected in the dataset I created. Currently when I change that word it replaces every entry in my dataset with the new word as opposed to just the specific entry. I am trying to figure how to specify just to change that one item.
That is because you are missing a WHERE clause in your query. You need to use a WHERE clause in your query to only update some selected records that you like :
eg : update dictionary set word=#word WHERE ID=#ID.
This is just an example. You have to put the WHERE clause as per your requirement.
Hope this helps.
Related
Using C# and Winform.
I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.
I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.
The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.
Beneath is the second user control that populates the datagridview
private void populate()
{
database.OpenConnection();
string query = "SELECT id, name, qoute, time, date from maintable";
SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
dtgNav.DataSource = ds.Tables[0];
databas.CloseConnection();
}
private void Navigation_Load(object sender, EventArgs e)
{
populate();
dtgNav.Columns[0].HeaderText = "ID";
}
public void Refresh()
{
this.Refresh();
}
Beneath is the code for adding a record to the datagridview in the first user control
private void btnAdd_Click(object sender, EventArgs e)
{
database.OpenConnection();
string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (#Id, #Name, #Qoute, #Time, #Date)";
SQLiteCommand command = new SQLiteCommand(query, database.connection);
command.Parameters.AddWithValue("#Id", tbxID.Text);
command.Parameters.AddWithValue("#Name", tbxName.Text.Trim());
command.Parameters.AddWithValue("#Qoute", tbxQoute.Text.Trim());
command.Parameters.AddWithValue("#Time", tbxTime.Text.Trim());
command.Parameters.AddWithValue("#Date", dtpDate.Value.ToString("yyyy-MM-dd"));
command.ExecuteNonQuery();
MessageBox.Show("Added new event into the database.");
database.CloseConnection();
usercontrol2.Refresh();
}
I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.
You have a public void Refresh method in the second usercontrol, try modifying this.Refresh();, to say populate();. this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.
I have two user controls. One is to input data and another one has a combobox that displays data from my MySQL table.
The use types in data in the first user control and presses a button. This adds the data to a MySQL table. I want to add the data immediately / automatically into the combobox (the other user control).
I would prefer not doing it using an event. If it is not possible and I have to use an event, what event should I use? Can it be an event not associated to the button?
Here is the method that reads data from MySQL and adds it to the combobox :
private void LoadFromDatabase()
{
string query = "select name from country";
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = new MySqlCommand(query,conn);
MySqlDataReader Read;
conn.Open();
Read = command.ExecuteReader();
while(Read.Read())
{
metroComboBox1.Items.Add(Read.GetString("name"));
}
conn.Close();
}
The current result is that I must reload the windows form to load the new data into thecombobox. Without the reload, the combobox only displays the old data. I have put that method under InitializeComponent(); of the combobox user control.
You can use the event click on the comboBox itself, so whenever you click it to open the dropdown it will update the combobox. Make sure to clear the items at the top of the click event to prevent duplicates.
If you truly insist on having no events, you can use a background worker, however for what you're doing it seems like overkill to spawn a thread just for that.
This is an idea of what the final result should look like.
private void comboBox1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
LoadFromDatabase();
comboBox1.SelectedItem = 0;
comboBox1.Text = "Select Item";
}
I need to update selected row in datagrid when i click on button Ponuda.
The problem is, when i click on button, nothing happens, but when i restart application, whole list is updated. So i need a way to update only the row i have selected and to update it right away and not after application restart.
This is my code for button click :
private void button3_Click(object sender, RoutedEventArgs e)
{
// count = 120;
// tmr.Start();
using (SqlConnection conn = new SqlConnection(#"data source=ZC-PC\SQLEXPRESS;database=Aukcija;integrated security=true;"))
{
DataTable cena1 = new DataTable();
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(" UPDATE Predmet SET trenutnaCena = trenutnaCena + 1", conn);
SqlCommand cmd = new SqlCommand("UPDATE Predmet SET trenutnaCena = trenutnaCena + 1", conn);
cmd.ExecuteNonQuery();
DA.Update(cena1);
conn.Close();
}
}
If you are using bindings, it SHOULD be updating. The reason it might not be is if whatever object your binding to the DataGrid (which should be an ObservableCollection or class based on one) does not implement INotifyPropertyChanged, the collection will never know a property change occurred.
If you haven't already, implement INotifyPropertyChanged and raise OnPropertyChanged event for each property. Then, when a value changes, it'll reflect both in the DataGrid and the actual collection being bound.
You'll want to make sure you have an event that updates the database with the new collection values whenever such and such happens (which I noticed button3_Click takes care of).
If this doesn't work, let me know, because it should.
So I've got a class, commenter, and two methods within that class, SaveBtn_Click - created primarily not by me, and then also PeerReview, primarily created by me.
Anyway, the code starts off like this (after a variety of using statements):
public partial class commenter : System.Web.UI.Page
{
string employee_reviewed;
PeerReview pr = new PeerReview();
public void SaveBtn_Click(object sender, EventArgs e)
{
//all the information for the SaveBtn_Click method.
}
After that, I have PeerReview:
public void PeerReview(System.Web.UI.WebControls.ListBox listbox)
{
MySqlConnection con = new MySqlConnection("server=localhost;database=hourtracking;uid=username;password=password");
MySqlCommand cmd = new MySqlCommand("select first_name from employee where active_status=1", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
Console.WriteLine("Another test!");
Console.WriteLine(r);
Console.WriteLine("Hi, this is a test!");
while (r.Read())
{
listbox.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));
}
con.Close();
}
I'm connecting this with ASP.NET, and I can get the listbox to show up, but not the individual items in the listbox. I'm testing it with a console.writeline command, to see if that outputs anything - but nothing is being put out on the ASP page.
I'm not certain how I should reference these particular sections (new to C#, asking like 3 dozen questions about this).
ASP code looks like this:
<asp:ListBox ID="listBox1" runat="server">
You have some confused declarations.
You declare a method called PeerReview, but you also have an attempt to create an instance of PeerReview as though it were a type. I think you really just want to call the PeerReview method from your button click event, eg
public void SaveBtn_Click(object sender, EventArgs e)
{
PeerReview();
}
And then eliminate the "PeerReview pr = new PeerReview();" line. Also, as this is on a page, you have an implicit reference within the partial class to the listbox by its ID, so you don't need to pass it as a parameter. And the Console.WriteLines are not useful in a web application - you might try Response.Write if you're wanting to add that to the output for debug purposes.
Edits based on OP response
You should call PeerReview in the Page_Load event handler:
public void Page_Load(object sender, EventArgs e)
{
// You need to determine if you should call PeerReview every time the page
// loads, or only on the initial call of the page, thus determining whether
// you need the IsPostBack() test. My instinct is that you *do* want to constrain
// it to the first pass, but only you can make that determination for
// certain based on your requirements.
if (!Page.IsPostBack) //Do you need this check?
{
PeerReview();
}
}
You're trying to add items to listbox though your listBox has an id of listBox1
Rather than looping through your data and adding items why not bind the datasource to your listbox and then set the DataTextField and DataValueField on your listbox.
So for example (typos may exist..sorry.. been a while since i wrote C#)
MySqlConnection con = new MySqlConnection("server=localhost;database=hourtracking;uid=username;password=password");
MySqlCommand cmd = new MySqlCommand("select first_name from employee where active_status=1", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
listBox1.DataSource = r;
listBox1.DataBind();
con.Close();
If you can't bind to the reader (can't remember..) then dump your results into a datatable first, then bind to the listBox1
DataTable dTable = New DataTable();
dTable.Load(reader);
listBox1.DataSource = dTable;
listBox1.DataBind();
in your asp, set the listBox fields like:
<asp:ListBox ID="listBox1" runat="server" DataTextField="first_name" DataValueField="first_name">
quick view here is you are adding items to listbox instead of listBox1
change:
listbox.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));
to:
listBox1.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));
im working in WinForms C#.
for some reason when I want to populate my listBox it stops and says my database is corrupt.
I have added a repair line and the codes run afterwards, but nothing happends. My listbox is not populated.
Here is the code im using.:
public void button1_Click(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = Database1.mdf");
cn.Open();
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM tblprojects ORDER BY Projekt_liste ASC", cn);
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListBox project_list = Application.OpenForms["Form1"].Controls["tabControl1"].Controls["tabPage1"].Controls["Project_list"] as ListBox;
project_list.Items.Add(dr["Projekt_liste"].ToString());
}
cn.Close();
cn.Dispose();
}
catch (Exception ex)
{
}
}
public void button2_Click(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection();
SqlCeEngine engine = new SqlCeEngine("Data Source = Database1.mdf");
if (false == engine.Verify())
{
MessageBox.Show("Database is corrupted.");
engine.Repair(null, RepairOption.RecoverAllPossibleRows);
}
}
For example if you want to load the items
1. make sure you have a ListBox on the winform
2. name the ListBox
3. Create a ListItem
4 Add the ListItem to the ListBox
while(dr.Read())
{
ListViewItem obj=new ListViewItem(Convert.ToString(dr[0]),Convert.ToString(dr[1]);
//in object of ListViewItem give display member at first and give value member at second position
listView1.Items.Add(obj); // add object to the listbox
}
Here are a few links that you can use as well to show different ways on how to populate a ListBox
one is Windows and the other will be if you are using or plan to use ASP.NET
Populate a ListBox when using SQLDataReader
asp.net SqlDataReader example: how to use Read() method to populate ListBox
Populate ASP.NET ListBox using SqlDataReader
From Microsoft Site
The Repair method does not guarantee complete data recovery for every
database. Some forms of data corruptions cannot be repaired
completely, regardless of the Repair option that is selected by the
application.
This could be one of the case where your file is corrupted.
Also please try To have repair call straight above the call to populate Data in List.
This may help.