I my class DBConnect, I have this function to populate a ComboBox to database based on input query:
public void POPULATE_COMBOBOX(string query, ComboBox myComboBox)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable myDataTable = new DataTable();
adapter.Fill(myDataTable);
myComboBox.DataSource = myDataTable;
this.CloseConnection();
}
}
And here's how I use it
DBConnect.POPULATE_COMBOBOX("SELECT NAME FROM users", comboBox_Name);
I have 3 rows in column NAME, and I expect those 3 names will be displayed in my comboBox_Name. However instead, I got 3 lines of System.Data.DataRowView in my combobox. Any idea how to convert those DataRowView to string?
You have to tell combobox what column to display.
//Preparation
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("Name1");
dt.Rows.Add("Name2");
//Setup data binding
myComboBox.DataSource = dt.DefaultView;
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Name";
Then SelectedItem gets the actual ComboBox item (in this case a DataRowView), whereas SelectedValue gets the value of the property you specified as the ValueMember of the ComboBox
Or another way how to populate your ComboBox is:
MySqlDataReader sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
myComboBox.Items.Add(sqlReader["Name"].ToString());
}
sqlReader.Close();
Related
My Form consist of a DataGridView and, inside of that, I have one Column as ComboBox.
The ComboBox is getting filled by the database query.
I wanted to display the default value of ComboBox in the DataGridView. I have loaded values in combo box but could not find a way to set a default value for that.
I have added values to a combo box with the following code on the click of the btnLoadCombo button:
private void btnLoadCombo_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);
//Filling ComboBoxes
con.Open();
SqlCommand cmdGetRootCat = new SqlCommand("SELECT * FROM tblProductCategories", con);
SqlDataReader sdaRootCat = cmdGetRootCat.ExecuteReader();
comboBoxCatTest.Items.Clear();
while (sdaRootCat.Read())
{
this.CatCombo.Items.Add(sdaRootCat["Cat_Name"]);
}
//Filling DataGridView
DataTable dt = new DataTable();
dt.Clear();
SqlCommand cmd = new SqlCommand("SELECT Cat_ID, Cat_Name FROM tblProductCategories", con);
SqlDataReader sda = cmd.ExecuteReader();
dt.Load(sda);
dataGridCatList.DataSource = dt;
con.Close();
}
I expect results as shown in image 2.
You can use
foreach(DataGridViewRow row in dataGridCatList.Rows)
{
if(row.Cells[3].Value != null) //ignore last row which is empty
{
if( row.Cells[3].Value.Equals(1018) )
row.Cells[0].Value = this.CatCombo.Items[0];
}
//...and so on
}
You are going through every row with the foreach() loop and compare the value of Cat_ParentCat with row.Cells[3].Value.Equals(Cat_ParentCatValue). If a match is found, set the default value of the ComboBox with row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];
I have a query that loads data from a MySQL db into a datagridview but in that same datagridview I have a combobox. The items list is being populated from another query. When the user first saves the data, he selects an item from the combobox and fills in the other columns by hand. The row is then saved with an insert query. What I want to do is display what was previously saved in the datagridview including the combobox choice. How do I go about showing the list item that was previously saved as the default item in the combobox?
here is the save code:
public void SaveOperations()
{
// create new row in project_operations with datagridview operations
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
MySqlCommand cmd = new MySqlCommand(#"insert into shopmanager.project_operations (products_product_id, operation_name, operation_description) values (#products_product_id, #operation_name, #operation_description)", con);
con.Open();
foreach (DataGridViewRow row in operation_dataGridView.Rows)
{
try
{
if (row.IsNewRow) continue;
cmd.Parameters.AddWithValue("#products_product_id", product_id.Text);
cmd.Parameters.AddWithValue("#operation_name", row.Cells["combo"].Value);
cmd.Parameters.AddWithValue("#operation_description", row.Cells["Description"].Value);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Operation Sauvegardé");
con.Close();
}
Here is the load code. This loads the data to the other cells in the row apart from the combobox. When I try to load the operation_name, it's creates a new column but what I want is for the operation name to be in the combobox. How can I achieve that?
private void LoadData()
{
// fill textbox columns
MessageBox.Show("load operations data textboxes");
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
DataTable dt = new DataTable();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand cmd;
cmd = new MySqlCommand(#"select operation_description as 'Description', operation_start_date as 'Début', operation_finish_date as 'Fin', users_employee_number as 'Employé' from shopmanager.project_operations where products_product_id = #product_id", con);
try
{
con.Open();
cmd.Parameters.AddWithValue("#product_id", product_id.Text);
cmd.ExecuteNonQuery();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
dt = ds.Tables[0];
operation_dataGridView.DataSource = dt;
cmd.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I think after setting the dataSource, I'll do like below (for both combo or check):
//ADD COLUMNS
var comboBox = new DataGridViewComboBoxColumn();
comboBox.HeaderText = "Header title";
comboBox.Name = "combo box";
var dataRow = new ArrayList();
foreach(var dr in dt.Rows)
dataRow.Add(dr["fieldName"].ToString()); // this will be the combo box data from database
// add data to combobox
comboBox.Items.AddRange(dataRow.ToArray());
// finally add the combo box to dgv
dataGridView1.Columns.Add(comboBox);
}
I am working with a simple application with c#
What I wan't to do is that when I retrieve data from SQL Database into Datagrid, i want some of rows to deleting by selecting them and then clicking a button.
The code i used to retrieve data is shown below:
SqlConnection conn = new SqlConnection("Server=MEO-PC;Database= autoser; Integrated Security = true");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From evidenc", conn);
DataTable dt = new DataTable("dtList");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dtg.ItemsSource = dt.DefaultView;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
conn.Close();
Also the code i tried for deleting the specific row is:
if (dtg.SelectedIndex >= 0)
{
dtg.Items.RemoveAt(dtg.SelectedIndex);
}
The erro i get is :Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
I don't know where is the problem cause I'am new to programming. Thanks to everyone
You need to remove the row from the DataTable. Try this:
DataRowView drv = dtg.SelectedItem as DataRowView;
if(drv != null)
{
DataView dataView = dtg.ItemsSource as DataView;
dataView.Table.Rows.Remove(drv.Row);
}
You can't remove an item from the Items collection when you have set the ItemsSource property.
You can use IEditableCollectionView to do this. You can directly change the underlying collection, if it allows changes to be made, by using the methods and properties that IEditableCollectionView exposes, regardless of the collection's type.
IEditableCollectionView iecv = CollectionViewSource.GetDefaultView(theDataGrid.ItemsSource) as IEditableCollectionView;
while (theDataGrid.SelectedIndex >= 0)
{
int selectedIndex = theDataGrid.SelectedIndex;
DataGridRow dgr = theDataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex) as DataGridRow;
dgr.IsSelected = false;
if (iecv.IsEditingItem)
{
// Deleting during an edit!
iecv.CommitEdit();
iecv.RemoveAt(selectedIndex);
}
else
{
iecv.RemoveAt(selectedIndex);
}
}
I used datagrid to show sql table datagrid.
And I showed one column on datagrid from sql.
Now I want to determine that which rows is now open & what is that values.
Like this.
See what I want to do.
And I used this code to show datatable on my datagrid.
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("cmt_7th");
sda.Fill(dt);
MydataGrid_roll.ItemsSource = dt.DefaultView;
}
And its show only row column. But I want to declare like my previous image.
You can get the selected row value with this code:
string em = dataGridView1.CurrentRow.Cells[2].FormattedValue.ToString();
You store the value in a string called em like the above, you can change the name for sure, and then cell[] is like an array, it stores each intersection of a row and a column in there, so for instance if you have 3 columns and two rows, the first intersection of the row and column is of index 0 and so on and so forth.
You could select all values that you are interested in up front of but only display the "roll" column in the DataGrid:
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT roll, tc, tf, pc, pf FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("cmt_7th");
sda.Fill(dt);
MydataGrid_roll.AutoGenerateColumns = false;
MydataGrid_roll.Columns.Add(new DataGridTextColumn() { Header = "roll", Binding = new Binding("roll") });
MydataGrid_roll.ItemsSource = dt.DefaultView;
}
You can then retrive any column values of the selected row in the DataGrid like this:
DataRowView drv = MydataGrid_roll.SelectedItem as DataRowView;
if(drv != null)
{
int selectedRoll = Convert.ToInt32(drv["roll"]);
if(drv["tc"] != DBNull.Value)
{
string selectedTc = drv["tc"].ToString();
}
//...
}
Here is my code:
SqlDataAdapter GridDataAdapter = new SqlDataAdapter(query, con);
DataSet GridDataSet = new DataSet();
GridDataAdapter.Fill(GridDataSet, tbln);
dataGridView1.DataSource = GridDataSet;
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dataGridView1.DataMember = tbln;
Here, I want to fetch data for DataGridViewComboBox from a database table column.
How can I fill the DataGridViewComboBoxColumn without using a DataReader?
You already have the dataset filled, you could just iterate over the row collection if it contains the values that you want the DGVCombo to contain. So, the most straightforward way would be something along the lines of:
foreach(DataRow r in GridDataSet.Tables[0].Rows)
{
dgvCB.Items.Add(r["MyColumn"]);
}
Where .Tables[0] has the column("MyColumn") that you are looking for...
This should be what you need...
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dgvCB.Name = "lastname";
dgvCB.DataSource = tbln;
dgvCB.HeaderText = "Last";
//uncomment this to actually select the value in the combo box
//dgvCB.DataPropertyName = "lastname";
dgvCB.ValueMember = "lastname";
dataGridView1.Columns.Add(dgvCB);