C# Combobox item text change? - c#

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.

Related

Cannot fill a Combobox in a Datagridview

I have a project and it need to choose database list on Combobox and show it in Datagridview. Here is my code :
private void Form2_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source= D:\Database\đồ án\Đồ án.mdb");
DataTable dt = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Sheet1", con);
da.Fill(dt);
da.Dispose();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tên đề tài";
comboBox1.ValueMember = "Mã đề tài";
}
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source= D:\Database\đồ án\Đồ án.mdb");
DataTable dt = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Sheet11 Where Mã đề tài = "+comboBox1.SelectedValue, con);
da.Fill(dt);
da.Dispose();
dataGridView1.DataSource = dt;
}
When I run this program and click on Combobox, it shows an error:
https://i.stack.imgur.com/C7DdZ.png
At first, I thought 2 sheets (tables) in database was not showing and didn't relationship but when I make it done and tried to start again, it shows an error again. How can I fix it ?
2 important notes:
Use parameters not string concatenation
It is bad practice to use spaces on column names. If you do, use brackets
Considering the above, try:
string query="Select * from Sheet11 Where [Mã đề tài] = #param";
OleDbCommand command = new OleDbCommand(query, con);
cmd.Parameters.Add(new OleDbParameter("#param", comboBox1.SelectedValue))
In addition to the 'spaces in column names' error you also got the order of the binding wrong when you set up the ComboBox.
You need to first set the members and only then the datasource. So change
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tên đề tài";
comboBox1.ValueMember = "Mã đề tài";
to:
comboBox1.DisplayMember = "Tên đề tài";
comboBox1.ValueMember = "Mã đề tài";
comboBox1.DataSource = dt;
Now not the whole table is bound but only the columns you want.
Before, the SelectedValue was not a single value but a whole DataRowView from which you would have to select the right item/column..
And, since it was a reference object, casting it to string (either implicitly with the + operator or explicitly with a ToString call) only resulted in the class name System.Data.DataRowView instead of a data value.
Further notes:
Avoid spaces in names of any kind; some moderen systems may work with them, but it will make the code less robust. The same goes for non-ascii characters.
While the values in your query here are only coming from the database, it is recommended to only use parameterized queries to avoid any sql injection.
Since you already have loaded the data into the DataTable you could just as well filter them without going back to the data base again. For this create a BindingSource or a DataView with a RowFilter and bind the DGV to it. For this, make the DataTable a class variable.

Devexpress GridView in Searchloookupedit use of

As shown in the picture below, the product I am looking for from the SearchLookupEdit object I added on Gridview
I want to add them to the related columns on Gridview.
Despite my research I have not found or used incorrect search words. I did not get it.
When SearchLookupEdit is selected, I want to insert the column named CARPAN in the Çarpan column on the Gridview.
The codes I use in the SearchLookupEdit object
DataTable Veri = new DataTable();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["STOK"].ConnectionString);
conn.Open();
SqlDataAdapter __Da = new SqlDataAdapter("select ID,AD,CARPAN from STOK_BIRIM order by ID desc", conn);
__Da.Fill(Veri);
repositoryItemSearchLookUpEdit1.DataSource = Veri;
repositoryItemSearchLookUpEdit1.DisplayMember = "AD";
repositoryItemSearchLookUpEdit1.ValueMember = "ID";
repositoryItemSearchLookUpEdit1View.Columns.Clear();
repositoryItemSearchLookUpEdit1View.Columns.AddVisible("AD", "BİRİM ADI");
repositoryItemSearchLookUpEdit1View.Columns.AddVisible("CARPAN", "CARPAN");
repositoryItemSearchLookUpEdit1View.Columns["CARPAN"].Visible = false;
conn.Close();

ComboBox SelectedItem shows System.Data.DataRowView

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);

combobox /dropdownlist in grid view c#.net

I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}

Put "ALL" on ComboBox[0] so that we filter it. NOTE: ComboBox has data from DB

For example, I have a Combo box with these contents coming from the database using SqlCommand, SqlDataAdapter and DataTable:
Japan
UK
USA
Philippines
Now, I want to add another choices. It should look like this:
----ALL----
Japan
UK
USA
Philippines
If I chose Japan, it will filter and show all the landmarks in the country like Mt. Fuji, Tokyo Tower.
If I chose UK, it will filter and show Big Ben, Westminster, Olympic Stadium.
If I chose USA, it will show fat people, Kim Kardashian.
IF I CHOSE ----ALL----, IT WILL SHOW ALL THE LANDMARKS FROM ALL COUNTRIES.
How do I do this? I'm using C# & SQL Server.
EDIT:
This is how I fill a combo box.
_con.Open();
SqlCommand _viewLandmarks = new SqlCommand("dbo.SelectDevices_AddingForm", _con);
_viewDevices.CommandType = CommandType.StoredProcedure;
_viewDevices.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(_viewLandmarks);
DataTable dTable = new DataTable("LANDMARK");
da.Fill(dTable);
comboModel.DataSource = dTable;
comboModel.DisplayMember = "Landmark";
comboModel.ValueMember = "LandmarkID";
_con.Close();
As said in comments it is just a matter to add a fake record in your returned datatable
_con.Open();
SqlCommand _viewLandmarks = new SqlCommand("dbo.SelectDevices_AddingForm", _con);
_viewDevices.CommandType = CommandType.StoredProcedure;
_viewDevices.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(_viewLandmarks);
DataTable dTable = new DataTable("LANDMARK");
da.Fill(dTable);
DataRow fakeRow = dTable.NewRow();
fakeRow["Landmark"] = "(ALL)";
fakeRow["LandmarkID"] = -1;
dTable.Rows.Add(fakeRow);
comboModel.DataSource = dTable;
comboModel.DisplayMember = "Landmark";
comboModel.ValueMember = "LandmarkID";
_con.Close();
I have added the open/close parenthesys around ALL to to force the new added row to the beginning of your datatable (assuming that it is sorted by Landmark).
Notice also that this approach assumes also that your fields are all NULLABLE. If one or more fields doesn't allow null values you need to set an appropriate value before adding the fakeRow to the Datatale rows collection
Just add a row in your datatable before binding and set the value to All.
Below is a example of binding the combo box
private void BindCombo()
{
DataTable dataTable = GetDataTable();
DataRow row = dataTable.NewRow();
row["Value"] = "0";
row["Name"] = "All";
dataTable.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = dataTable;
}

Categories