ComboBox SelectedItem shows System.Data.DataRowView - c#

I insert data from my database to combobox, and now I want to display value of this combobox into label, but every time instead of getting value of combobox, I get System.Data.DataRowView in my label.
I use this code for connection, it works fine:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "library";
sb.Password = "library";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleDataAdapter TITLES = new OracleDataAdapter("SELECT NAME FROM TITLE", conn);
DataTable dt = new DataTable();
TITLES.Fill(dt);
cmbBooks.DisplayMember = "NAME";
cmbBooks.DataSource = dt;
conn.Close();
And then I want to get SelectedItem using this code:
label1.Text = cmbBooks.Items[cmbBooks.SelectedIndex].ToString();
How to solve it?

You can use the GetItemText method:
label1.Text = cmbBooks.GetItemText(cmbBooks.SelectedItem);

Related

How to hide unnecessary columns in the GridControl?

Winform has 2 grids. I display related tables from the SQL Server database to them.
Here is the code:
string connectionString = ConfigurationManager.ConnectionStrings["connectionSIPiT"].ConnectionString;
string command = "SELECT UserID, UserName,Login, idArm FROM Users";
string command2 = "SELECT id, name FROM arm";
sqlConnection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(command2, sqlConnection);
SqlDataAdapter adapter1 = new SqlDataAdapter(command, sqlConnection);
DataSet dataset1 = new DataSet();
adapter.Fill(dataset1, "arm");
adapter1.Fill(dataset1, "Users");
DataColumn keyColumn = dataset1.Tables[0].Columns[0];
DataColumn foreignKeyColumn = dataset1.Tables[1].Columns[3];
dataset1.Relations.Add("armUsers", keyColumn, foreignKeyColumn);
bindingSource1.DataSource = dataset1;
bindingSource1.DataMember = "arm";
bindingSource2.DataSource = bindingSource1;
bindingSource2.DataMember = "armUsers";
gridControl1.DataSource = bindingSource1;
gridControl2.DataSource = bindingSource2;
Please help me figure out how to hide unnecessary columns in the GridControl. Such as Id) Can the DataTable be used? If possible an example
After you set the DataSource for both grids, you can set the Visible property for the Id column to false.
Assuming the DefaultView is a GridView, the following code should do the job.
(gridControl1.DefaultView as GridView).Columns["Id"].Visible = false;

C# Combobox item text change?

I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?
This is my code:
private void getAdr()
{
string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = #userID", conn);
SqlParameter parUserID = new SqlParameter("#userID", Login.id);
getAdr.Parameters.Add(parUserID);
getAdr.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(getAdr);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "adressID";
comboBox1.ValueMember = "adressID";
textBox5.DataBindings.Add("Text", dt, "adress");
textBox6.DataBindings.Add("Text", dt, "floor");
textBox7.DataBindings.Add("Text", dt, "city");
textBox8.DataBindings.Add("Text", dt, "state");
textBox9.DataBindings.Add("Text", dt, "country");
textBox10.DataBindings.Add("Text", dt, "zipcode");
comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";
}
I think you should implement the TextChanged event of the combobox. When the user changes the addressID you should update your DB by using SqlCommand and then reload the datasource to refresh the combobox items.
When you set datasource property what you must change is that property and automatically your changes are visible in the combo.
For doing that i recommend you to use BindingSource object like this:
BindingSource Adresses = new BindingSource();
Adresses.DataSource = dt;
comboBox1.DataSource = Adresses;
comboBox1.DisplayMember = "adressID";
comboBox1.ValueMember = "adressID";
When you change some data in dt object you should call:
Adresses.ResetBindings(true);
To updtate combo's data.

Get string value of the GridView cell on click

I have DataGrid that shows some values from MySQL database. I need that if I click on any column, the value will be saved to string. Is it even possible?
Here´s the code that shows mysql table in the datagrid
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select Jméno from info", conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "LoadDataBinding");
dataGridCustomers.DataContext = ds;
}
catch
{
WarnWindow vv1 = new WarnWindow(1);
vv1.ShowDialog();
}
finally
{
conn.Close();
}
But if I click on (for example) Bohumil Homola, this value shall be saved as:
string name = Bohumil Homola (column value);
Finally I got it. Here´s the code which I used:
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)datagridname
.ItemContainerGenerator
.ContainerFromIndex(datagridname.SelectedIndex);
DataGridCell RowColumn = datagridname.Columns[0].GetCellContent(row).Parent as DataGridCell;
string ContentOfCell = ((TextBlock)RowColumn.Content).Text;

How to set combobox value to null or empty while loading data to it from database in c#.net

I have a windows form coded in c#..
the problem is I have a combobox which is loaded values from database,and that code has written in LOAD form..
so,my form's combobox values are generated automatically to it and the Initial combobx text is loaded to it..
I want to set combobox initial text or value should be empty or null..
please help me to solve it..
Thanx in advance
my code is as follows
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name,image from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
//Convert.ToString.comboBox1.Items.Insert("", 0);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
//dateTimePicker1.Enabled = true; ;
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
Add this line after you set your datasource to db:
comboBox1.SelectedItem = null;
Or
comboBox1.SelectedItem = -1;
do not make it null, better to writer it Select as selected value.
`dt.Load(dtr);
DataRow drow = dt.NewRow();
drow[0] = "-1";
drow[1] = "Select";
drow[2] = string.Empty;
dt.Rows.InsertAt(drow, 0);
dt.AcceptChanges();
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;`

how to trigger an event when an item is selected from combobox in c#.net

string Sql_type = "select property_type_id,type_name from lk_tb_property_type";
OleDbCommand cmd_type = new OleDbCommand(Sql_type, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
//begin adding line
DataRow row_two = table_two.NewRow();
row_two["type_name"] = "Select Poperty Name";
row_two["property_type_id"] = 0;
table_two.Rows.InsertAt(row_two, 0);
//end adding a line
combo_type.DataSource = table_two;
combo_type.DisplayMember = "type_name";
combo_type.ValueMember = "property_type_id";
combo_type.Text = "Select Poperty Name";
with this code i am fetching values for a combobox from database.now suppose my combobx is having 2 items named A and B..I have one more combobox...now what i want is that when user chooses item A from combobox the second combobox should display data related to item A when user chooses item B then data related to item B should be displayed...sohow to achieve this...??
you can fetch the data and bind it to combobox2 on SelectedIndexChanged event of combobox1
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
var val = combobox1.SelectedValue;
// fetch data from database
// you need to set SQL parameter value form SelectedValue
combobox2.DataSource = ...; // set this value
combobox2.DisplayMember = .....; // set this value
combobox2.ValueMember = ....; // set this value
}
Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#
In SelectedIndexChanged of combo box write your code. and make AutoPostBack = true of your combobox
You can do like these steps.
First, bind data to comboBox1 (I suppose that your first ComboBox named "comboBox1", and your form named "Form1"), please make sure that your SQL query command is correct for comboBox1
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_cust_name = "select customer_name from tb_customer";
OleDbCommand cmd_cust_name = new OleDbCommand(Sql_cust_name, con);
OleDbDataReader DR_cust_name = cmd_cust_name.ExecuteReader();
DataTable table_cust_name = new DataTable();
table_cust_name.Load(DR_cust_name);
DataRow row_cust_name = table_cust_name.NewRow();
row_cust_name["customer_name"] = "Select Customer Name";
table_cust_name.Rows.InsertAt(row_cust_name, 0);
combo_cust_name.DataSource = table_cust_name;
combo_cust_name.DisplayMember = "customer_name";
combo_cust_name.ValueMember = "customer_name";
combo_cust_name.Text = "Select Customer Name";
con.Close();
}
Next, bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed, this value will be used in the filtering for data in comboBox2, so you have to handle SelectedIndexChanged event for comboBox1, please make sure that you have this code somewhere in your project: this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
To bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed
private void combo_cust_name_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string customerName = "";
if (combo_cust_name.SelectedValue.GetType() == typeof(DataRowView))
{
DataRowView selectedRow = (DataRowView)combo_cust_name.SelectedValue;
customerName = selectedRow["customer_name"].ToString();
}
else
{
customerName = combo_cust_name.SelectedValue.ToString();
}
string Sql2 = "SELECT customer_number FROM tb_customer WHERE customer_name = '" + customerName + "'";
OleDbCommand cmd_type = new OleDbCommand(Sql2, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
DataRow row_two = table_two.NewRow();
row_two["customer_number"] = "Select Customer Number";
table_two.Rows.InsertAt(row_two, 0);
comboBox2.DataSource = table_two;
comboBox2.DisplayMember = "customer_number";
comboBox2.ValueMember = "customer_number";
comboBox2.Text = "Select Customer Number";
}
Please correct the SQL query command as you want, but don't forget to put a correct filter like my sample code above.

Categories