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.
Related
I know it's been asked many times and there's so many resources about this but believe me i tried those, Unfortunately same thing is always happen. I really don't know why my combo box column value is repeating. Can someone help me in doing these in a proper way. Did i forgot something here ? Thank you
public void FillComboBox()
{
using (var con = SQLConnection.GetConnection())
{
using (var cmd = new SqlCommand("SELECT * FROM employee_product", con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
}
}
}
}
Here's the provided image
If you check the code, you are basically just adding the strings "Code", "Model" and "Itemdescription" to the combobox. I guess you want rather something like:
while (reader.Read())
{
cbox_order.Items.Add($"{reader["Code"]} {reader["Model"]} {reader["Itemdescription"]}");
}
In this snippet I am using the reader to get values of the columns in the returned row from the DB and then displaying joining those values in a single string that is then added to the ComboBox as an item.
Update
If you know the column names, why not just do this?
public void FillComboBox()
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
First load data into a DataTable:
var connection = #"Your connection string";
var command = "Your SELECT command text";
var table = new DataTable();
using (var adapter = new SqlDataAdapter(command, connection))
adapter.Fill(table);
To show list of columns in a ComboBox:
comboBox1.DataSource = table.Columns.Cast<DataColumn>().ToList();
comboBox1.ValueMember = "ColumnName";
comboBox1.DisplayMember = "ColumnName";
To show data in DataGridView:
dataGridView1.DataSource = table;
In above code I suppose you are going to show columns of the table which you also want to load its data at the same time. In case which you just want to load just column information, you can use:
adapter.FillSchema(table, SchemaType.Mapped);
actually your not using your DataReader but you just add Code, Model and ItemDescription item for each row found with the MySQL query.
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
If you want to use the result of the MySQL query you can try this instead:
cbox_order.Items.Add(reader["Code"].ToString()).ToString(); // Change "Code" by the column name into the database
cbox_order.Items.Add(reader["Model"].ToString()).ToString(); // Change "Model" by the column name into the database
cbox_order.Items.Add(reader["Itemdescription"].ToString()).ToString(); // Change "Itemdescription" by the column name into the database
Don't forget to close the reader at the end
reader.Close();
EDIT
if you want the column name instead of data you can use this query, but that's useless if you already know the column name.
SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema='databasename' AND table_name='tablename'
Try to close and dispose of reader and close the connection.
reader.close;
reader.dispose;
con.close();
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.
I know that it sounds wrong. Is It possible to get the SQL value on the dropdown list anyway, so that one of the ListItem in dropdownlist is similar to SQL.
here is my code:
private void ReviewButtonPinsDetails()
{
con.Open();
cmd = new SqlCommand(#"SELECT quo_ProdCategory,quo_ProdType
,quo_JobDesc,quo_PrintProcess
,quo_File,quo_Finishing
,quo_Quantity
FROM JobQuotations1
WHERE TransactionID = #id
AND TransactionNum = #Num", con);
cmd.Parameters.AddWithValue("#id", GridView1.SelectedRow.Cells[2].Text);
cmd.Parameters.AddWithValue("#Num", GridView1.SelectedRow.Cells[4].Text);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
ddlProducts.Text = rdr["quo_ProductCategory"].ToString();
ddlProdName.Text = rdr["quo_ProdType"].ToString();
txtJobDesc.Text = rdr["quo_JobDesc"].ToString();
ddlPrintProc.Text = rdr["quo_PrintProcess"].ToString();
lblFileName.Text = rdr["quo_File"].ToString();
txtFinishing.Text = rdr["quo_Finishing"].ToString();
txtQty.Text = rdr["quo_Quantity"].ToString();
}
}
con.Close();
lblFileStatus.Text = "Previous File";
}
When the customer wanted to review His/Her order and select the row on grid view It suppose to restore the value of The textboxes and dropdownlist.
I don't quite understand the framework that you are working in but have you considered using the functionality offered by the INotifyPropertyChangedinterface.
Which will allow you to use the PropertyChangedEventHandler object.
Bind the textbox in the view to a property in your model.
You could then create some properties in the class that will hold the data for the text boxes and dropdowns and ensure that when a new property is set the
PropertyChangedEventHandler object you have created will handle updating the property in the view.
First bind your dropdownlist before Sql Value assign to it.
For example:
bindProducts(ddlProducts);
ddlProducts.SelectedValue = rdr["quo_ProductCategory"].ToString();
bindProducts(ddl as DropDownList) is the method for bind the product list to dropdownlist.
After using inner joins and fetching data from 3 tables I want to show course names that are assigned to Miss Jennifer whise Tchr_ID is 4 , ddlcourse is dropdown list id
SqlCommand cmd = new SqlCommand(#"
SELECT
Course.Course_name,
Tchr_course_ID
FROM Course
INNER JOIN CourseOffering
ON Course.Course_ID=CourseOffering.Course_ID
INNER JOIN Tchr_Course
ON Tchr_Course.Course_offer_ID=CourseOffering.Course_offer_ID
where Tchr_Course.Tchr_ID = 4", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlcourse.DataSource = dr;
ddlcourse.Items.Clear();
ddlcourse.DataTextField = "Course_name";
ddlcourse.DataValueField = "Tchr_course_ID";
ddlcourse.DataBind();
After fetching I am showing dropdown textfield as course name and I am applying datavaluefiled as tch_Course_ID because when user will select the course , its tchr_course_ID will be saved in db. to save id I am using ddlcourse.SelectedItem.Value but this gives me error in my insert statement about foreign key. It is not taking value of selected course. Why? and how can I correct it?
These tables are involved in it..
Course table:(which have courses list in it) ==>
(Course_ID,Course_name)
CourseOffering table: (which have record that these courses are
offered this semester) ==> > (Course_offer_ID, Course_ID)
Tchr_Course table: (which have record that this course is assigned to
this teacher) ==> (Tchr_course_ID, Course_offer_ID, Tchr_ID)
Profile table: (simple contains teacher record) == >
(Tchr_ID,NAme,Email)
Use SelectedValue instate of using SelectedItem.Value since ur ddlcourse has DataValueField as Tchr_course_ID hence only SelectedValue gives u required result for Tchr_course_ID.
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();