Update values in a combobox from mysql - c#

I have a ComboBoxColumn in my datagridview and the data that's bound to them is from another table. The data can be updated at any point so I want to update the data in the ComboBoxColumn automatically when the data is added/updated from another table.
I've tried using -
ScripterCombo.DataSource = updatedUserList;
updatedUserListis a list of the data that i want to apply to the ComboBoxColumn, I already set the DataSource of ComboBoxColumn. Unfortunately the ComboBoxColumn never update. I need to reload the entire application to view the changes.
UPDATE -
Sorry i'm not using a list to store the data, i'm using a string array. Basically i connect to the backend server and loop through all the names in the 'User' Column:
MySqlConnection(Constants.serverInfo))
{
getNumberOfUsers.Open();
using (MySqlCommand requestCommand = new MySqlCommand("SELECT COUNT(*) FROM userlist", getNumberOfUsers))
{
MySqlDataReader userReader = requestCommand.ExecuteReader();
while (userReader.Read())
{
iNumberOfUsers = userReader.GetInt32(0); // Pull the number of Owners from the backend.
strListOfUsers = new string[iNumberOfUsers]; // Make sure the owner list can hold the value pulled from the backend.
}
userReader.Close();
}
getNumberOfUsers.Close();
}
// Get the names of the users
using (MySqlConnection getUsersNames = new MySqlConnection(Constants.serverInfo))
{
getUsersNames.Open();
using (MySqlCommand requestCommand = new MySqlCommand("SELECT username FROM userlist", getUsersNames))
{
MySqlDataReader userReader = requestCommand.ExecuteReader();
for (int i = 0; i < iNumberOfUsers; i++)
{
while (userReader.Read())
{
strListOfUsers[i] = userReader.GetString(0); ; // Add the user to the list of users.
i++;
}
}
userReader.Close();
}
getUsersNames.Close();
}
I have another class that grabs data from a different table and displays it in a datagridview. I then feed the array of users through to the above class and create a datagridcomboboxcolumn that displays all the usernames. This works as expected, as it displays the user list and then updates the main table when a user has been changed.
However, if i add a user to the list I call the above code again to get an updated list and then feed the list to the comboboxcolumn using this -
ScripterCombo.DataSource = updatedUserList;
This unfortunatly doesn't update the comboboxes, but when I check the DataSource after running this it's showing the newly added user. It just doesn't want to display it.
Hope this makes sense.
Thanks

try to add ToList()
ScripterCombo.DataSource = updatedUserList.ToList();

Related

SQLite error Insufficient parameters supplied to the command

When trying to change the active column in the following table 1.
I get the error
Error insufficient parameters supplied to the command
and I cannot figure out for the life of me what is wrong with the code. Please help.
private void dataGridView1_SelectionChanged_1(object sender, EventArgs e)
{
SQLiteConnection sqlConnection = new SQLiteConnection();
sqlConnection.ConnectionString = "datasource = SubjectTable.db";
if (dataGridView1.SelectedRows.Count > 0)
{
ID = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
//Define SELECT Statement
string commandText = "SELECT * FROM SubjectTable WHERE ID=" + ID;
//Create a datatable to save data in memory
var datatable = new DataTable();
SQLiteDataAdapter myDataAdapter = new SQLiteDataAdapter(commandText, sqlConnection);
sqlConnection.Open();
//Fill data from database into datatable
myDataAdapter.Fill(datatable);
//Fill data from datatable into form controls
CMBactive.Text = datatable.Rows[0]["Active"].ToString();
TBsubjectBUD.Text = datatable.Rows[0]["Budget"].ToString();
sqlConnection.Close();
}
}
You are getting these problems, because you are trying to do too much things in one procedure. You should separate your concerns
Separate the fetching of the data from the database from displaying this data; separate also that you do this of event selection changed.
This has the advantage that you can reuse your code more easily: if you want to do the same because of a Button press, you can reuse the code. After that it is a one-liner code if you want to add a menu item doing the same.
It is easier to test your code if you have a separate method to query the database, or a separate method to fill your controls CmbActive and TbSubjectBud.
It is easier to change your code, for instance, if you will not use SQLite anymore, but entity framework to fetch your data, the displaying and the button handling won't notice this. Only the procedure to fetch the data needs to be changed.
This makes unit testing easier: instead of a real database, you can mock the database with a Dictionary for the tests.
Finally: when using Winforms, don't fiddle with the Cells directly, use the DataSource of the DataGridView to fill and read the data. Again: separate the data from how it is displayed.
First Your actual problem: query the data
So you have an Id, and you want to fetch the values of columns Active and Budget from all Subjects from the database that have this Id. Don't fetch properties that you won't use!
Database handling
First we need a class Subject to put the data that you fetch from table SubjectTable. If you put all columns of this table in it, you can reuse the class for other queries. However. you don't have to fill in all fields. It depends how often you will call this method whether it is wise to fill all properties or only some.
Some people don't like this. Consider to fetch always all columns (inefficient), or to create classes for different queries (a lot of work).
class Subject
{
public int Id {set; set;}
public string Name {get; set;}
public DateTime StartDate {get; set;}
public string Active {get; set;}
public Decimal Budget {get; set;}
}
Create a method to fetch the Active and Budget from tableSubjects with Id, or null if there is not subject with this Id.
Put all your database queries in a separate class. For instance class Repository. You hide that it is in a database, if in future you want to save it in a CSV-file, or JSON format, no one will notice (nice if you want to use it in a unit test!)
private Subject FetchBudgetOrDefault(int id)
{
const string sqlText = #"SELECT Active, Budget FROM SubjectTable WHERE ID = #Id";
using (var dbConnection = new SQLiteConnection(this.dbConnectionString))
{
using (var dbCommand = dbConnection.CreateCommand()
{
dbCommand.Commandtext = sqlText;
dbCommand.Parameters.AddWithValue("#Id", id);
using (var dbReader = dbCommand.ExecuteReader())
{
if (dbReader.Read())
{
// There is a Subject with this id:
return new Subject()
{
Id = id,
Active = dbReader.GetString(0),
Budget = (decimal)dbReader.GetInt64(1) / 100.0D,
};
}
else
{
// no subject with this Id
return null;
}
}
}
}
}
I assumed that the decimal Budget is saved as long * 100 on purpose, to show you that by separating your concerns it is fairly easy to change the database layout without having to change all users: if you want to save this decimal in SQLite as a REAL, then the queries are the only place where you have to change the data.
By the way: this method also solved your problem: ID can't be an empty string!
If you won't do this query 1000 times a second, consider to fetch all columns of Subject. This is a bit less efficient, but easier to test, reuse, and maintain.
Display the fetched data in your form
Currently you display the data in a ComboBox and a TextBox. If you separate your concerns, there will only be one place where you do this. If you want to display the data in a Table, or do something else with it, you only have to change one place:
public void Display(Subject subject)
{
this.comboBoxActive.Text = subject.Active;
this.textBoxBudget.Text = subject.Budget.ToString(...);
}
Bonus points: if you want to change the format of the displayed budget, you'll only have to do this here.
Read and Write the DataGridView
It is seldom a good idea to read and write the cells of a DataGridView directly. It is way to much work. You'll have to do all type checking yourself. A lot of work to test and implement small changes in the displayed data.
It is way easier to use the DataSource.
In the DataSource of the DataGridView you put a sequence of similar items. If you only want to Display once, an ICollection<TSource> will be enough (Array, List). If you want to update changes automatically, use a BindingList<TSource>
In the DataGridView add columns. User property DataGridViewColumn.DataPropertyName to indicate which property should be displayed in that column.
Usually it is enough to use visual studio designer to add the columns.
If your datagridview displays Subjects, code will be like:
DataGridView dgv1 = new DataGridView();
DataGridViewColumn columnId = new DataGridViewColumn
{
DataPropertyName = nameof(Subject.Id),
...
};
DataGridView columnName = new DataGridViewColumn
{
DataPropertyName = nameof(Subject.Name),
...
};
... // other columns
dgv.Columns.Add(columnId);
dgv.Columns.Add(columnName);
...
In your forms class:
private BindingList<Subject> DisplayedSubjects {get; set;} = new BindingList<Subject>();
// Constructor:
public MyForm()
{
InitializeComponent();
this.dgv1.DataSource = this.DisplayedSubjects();
}
void FillDataGridView()
{
using (var repository = new Repository())
{
IEnumerable<Subject> fetchedSubjects = repository.FetchAllSubjects();
this.DisplayedSubjects = new BindingList<Subject>(fetchedSubjects.ToList();
}
}
This is all that is needed to display all fetched subjects. If the operator changes any cell value, the corresponding value in this.DislayedSubjects is automatically updated.
This works both ways: if you change any value in this.DisplayedSubjects, the displayed value in the DataGridView is automatically updated.
No need to read the cells directly. If you allow column reordering, or if you implement row sorting, then everything still works two ways. Because you separated the fetched data from the displayed data, you can change the display without having to change the fetched data.
Put it all together
When you get the event that the selection is changed from the datagridview you want to update Active and Budget. Let's do the from the Selected item:
void OnSelectionChanged(object sender, EventHandler e)
{
// Get the selected Subject
var selectedSubject = this.SelectedSubject;
this.Display(selectedSubject); // described above
}
Subject SelectedSubject => this.Dgv.SelectedRows.Cast<DataGridViewRow>()
.Select(row => (Subject)row.DataBoundItem)
.FirstOrDefault();
Because you separated concerns, each method is easy to understance, easy to test, easy to reuse and to change slightly: if you want to update after a Button Press or a menu item, the code will be a one liner. If you want to display other items than just Active / Budget: small changes; if you want to fetch by Name instead of Id: only limited changes needed.

C# ListBox : Items collection cannot be modified when the DataSource property is set

I have created following function to call for delete the selected record from database
and also from the listbox, which will get call on button Delete Record.
Function:
void DeleteListBox2()
{
string connstring = String.Format("Server=localhost;Port=***;" +
"User Id=****;Password=****;Database=****;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
for (int i = 0; i < listBox2.SelectedItems.Count; i++)
{
var itemname = listBox2.SelectedValue;
NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM Table WHERE Value = '" + itemname + "'", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Selected record deleted from database");
listBox2.Items.Remove(listBox2.SelectedItems[i]); //ERROR LINE
listBox2.Update();
}
conn.Close();
}
ERROR:
Items collection cannot be modified when the DataSource property is set.
It would help to provide additional details such as what frameworks you are using, WPF, Winforms etc.
Your ListBox should have its data source bound to a List object. Then instead of deleting directly from the list view component, you should delete from the List that the view is bound to and then notify the UI that there are changes and it will update accordingly.
Here is a good read on binding your list view to a list object:
Binding Listbox to List
A quick google search will return results on how to update UI once changes have been made, here is one for winforms:
How to refresh DataSource of a ListBox in C# WinForms
I would suggest after you delete the items in the database to read it again. Since you probably want to have a recent mapping from database to the display.
After that just reattach the DataSource property to the new record collection.

New record isn't loading until application restarted using C# with MySQL

I'm using a MySQL database with a C# application. I have the application set to use a form to add a new record and display existing records. Once a record is inserted, the form should re-grab records from the database, and display the last record in the table in the form (ie. the newly created record).
As it stands, it's showing the first record as the first and last record when clicking on previous/next or first/last to browse through the records in the table. It seems to be looping the the first one in the data adapter for some reason. I'm new to using MySQL with C#. Is there a way that this can be reset or updated without having to restart the application?
To populate the form, it's calling the same method as on form load, connecting to the database, getting the row count, filling the data adapter, populating the text boxes, and then closing the connection to the database. Not sure why it can't grab everything the second, etc, time around.
When the user clicks add to add the new record:
//Recounts rows in table in the table
numberOfRows = GetRowCount("tblTable");
//Resets displayedRow counter and updates form data to show new record
displayedRow = numberOfRows - 1;
UpdateFormData(displayedRow);
The number of records is updating on the form properly, so I know that's working alright.
Then in the UpdateFormData method:
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM `tblTable`;";
cmd.ExecuteNonQuery();
//Fill DataAdapter
using (tblTableDataAdapter = new MySqlDataAdapter(cmd))
{
tblTableDataAdapter.Fill(tblTableDataTable);
}
tblTableDataAdapter = new MySqlDataAdapter(cmd.CommandText, connection);
tblTableDataAdapter.Fill(tblTableDataSet);
//Displays row data in textbox
textBox1.Text = tblTableSet.Tables[0].Rows[displayedRow]["FirstName"].ToString();
textBox2.Text = tblTablefDataSet.Tables[0].Rows[displayedRow]["LastName"].ToString();
textBox3.Text = tblTableDataSet.Tables[0].Rows[displayedRow]["StaffAddress"].ToString();
textBox4.Text = tblStaffDataSet.Tables[0].Rows[displayedRow]["PostalCode"].ToString();
textBox5.Text = tblTableDataSet.Tables[0].Rows[rowNumber]["City"].ToString();
textBox6.Text = tblTableDataSet.Tables[0].Rows[rowNumber]["Phone"].ToString();
textBox7.Text = tblTableDataSet.Tables[0].Rows[rowNumber]["Email"].ToString();
Okay, I figured out the problem. The dataset needed to be reset before refilling the data adapter. Changed the update method to include:
tblTableDataSet.Reset();
tblTableDataAdapter = new MySqlDataAdapter(cmd.CommandText, connection);
tblTableDataAdapter.Fill(tblTableDataSet);
And it's showing the new record now.

How to cache a datagridview in windows forms application

I am working on an application in which data is retrieved from four SQL tables using joins and the retrieved data is populated to a datagridview on a windows form.
I have two Radio Buttons ALL and DrawDate , by default ALL Radio Button is selected and once the application is opened it populates all the data on to the datagridview and when I select DrawDate Radio Button, only the data related to that draw date is populated on the datagridview. Everything looks fine until then but after selecting DrawDate Radio Button and if a user want to get all the data again by selecting ALL Radio Button, it again loads all data from the database server which is not preferred.
Is there any better way I can cache the data populated once the application is opened and populate it when a user selects ALL Radio Button later when he needs it?
C# Code
sqlcon = GetConnectionString();
try
{
sqlcon.Open();
//var sw = Stopwatch.StartNew();
for (int i = 0; i < dgvPaymentsReceived_Collections.RowCount; i++)
{
int trademonth = Convert.ToInt32(dgvPaymentsReceived_Collections.Rows[i].HeaderCell.Value);
for (int j = 0; j < dgvPaymentsReceived_Collections.ColumnCount; j++)
{
int paymentmonth = Convert.ToInt32(dgvPaymentsReceived_Collections.Columns[j].HeaderCell.Value);
//var sw = Stopwatch.StartNew();
SqlCommand cmd_PaymentsReceived = new SqlCommand();
cmd_PaymentsReceived.Connection = sqlcon;
cmd_PaymentsReceived.CommandType = CommandType.StoredProcedure;
cmd_PaymentsReceived.CommandText = sp_PaymentsReceved_Collections;
cmd_PaymentsReceived.Parameters.Add(new SqlParameter("#trademonth", trademonth));
cmd_PaymentsReceived.Parameters.Add(new SqlParameter("#paymentmonth", paymentmonth));
SqlDataAdapter da_PaymentsReceived_Collections = new SqlDataAdapter();
DataTable dt_PaymentsReceived_Colletions = new DataTable();
da_PaymentsReceived_Collections.SelectCommand = cmd_PaymentsReceived;
da_PaymentsReceived_Collections.Fill(dt_PaymentsReceived_Colletions);
//sw.Stop();
//MessageBox.Show(sw.ElapsedMilliseconds.ToString());
dgvPaymentsReceived_Collections.Rows[i].Cells[j].Value = dt_PaymentsReceived_Colletions.Rows[0][0].ToString();
}
}
sqlcon.Close();
}
You haven't shown us any code. What kind of connection did you use? Don't bind your database source to a datagridview - use either an Enumerable/IList collection or DataSet as your data holder and then assign only the part of it (filtering it with LINQ) to your datagridview. This way you don't have to create a new collection every time in memory, just iterate over the items with given condition.
Assuming you don't have tons and tons of data, you could store the SQL results in a DataTable and then bind that to the DataGridView
You could consider storing the SQL data in a IEnumerable data structure when All button is clicked, and bind that collection to the gridview, and during the DrawDate button click, sort the collection appropriately.
You can hang on to your original data table and create a separate DataTable to bind to your DataGridView if you want to be able to change what is displayed.
Just fill your data table once, and then create a new DataTable to hide what you don't need.
This might use slightly more memory depending on the size of your DataTable, but it's probably the easiest solution to implement.
DataTable viewedData = dt_PaymentsReceived_Colletions;
if(hideIncome.Checked) {
viewedData.Columns.Remove("Income");
viewedData.AcceptChanges();
}
DataGridView1.DataSource = viewedData;

problem updating dropdownlist

I have a problem while updating changing the item in dropdownlist.
I have a dropdownlist which is populated in code behind file.
Here is the code:
departmentComm = new SqlCommand("SELECT DepartmentID, Department FROM Departments", conn);
conn.Open();
reader = departmentComm.ExecuteReader();
// Populate the list of categories
departmentList.DataSource = reader;
departmentList.DataValueField = "DepartmentID";
departmentList.DataTextField = "Department";
departmentList.DataBind();
// Close the reader
reader.Close();
I select one value from this list and saves it in my employee table. Now let's suppose I want to update this value in employee table.
Now my question is, how can I pull this value in dropdownlist and show it?
If you just van to get the selected department id:
departmentList.SelectedValue
gives you the id
If you embedded the dropdown in a datagrid you will need to update the database using a DataAdapter and call its Update method.
If you need more specifics you need to give more details.

Categories

Resources