I am writing a small application in C# using windows forms. I have a combo box that I am populating by querying a database for column names to use as the values inside the combo box. My code currently can get the values just fine, however whenever I click on the combo box it removes any text and just displays a blank 'selected option'. I have tried multiple things to correct this (changed the database field from char to varchar), tried binding to a different dataset etc. but nothing has worked. Ive also looked at other posts on this such as
C# comboBox databinding - nothing happens, then it goes back to blank
Below is my code, and I believe I am doing the displaymember/valuemember part wrong however I do not understand what it is that is wrong. The column name in the database is Reason and it consists of 3 values.
Any help is appreciated.
String ConnString = ConfigurationManager.ConnectionStrings["Portal1"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
SqlCommand sc = new SqlCommand("select [Reason] from tblReasons", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Reason", typeof(string));
dt.Load(reader);
cboxReason.ValueMember = "Reason";
cboxReason.DisplayMember = "Reason";
cboxReason.DataSource = dt;
conn.Close();
Your code looks OK. I would not add the column, that should happen automatically. Here is my sample code that works:
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
var reader = new SqlCommand("select ID from Users", conn).ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = dt;
conn.Close();
Note: This populates with the list of values in the column. For the list of column names, I would suggest changing your query to return a list of columns for the table (DB specific query) OR look at the DataTable.Columns collection for the column names.
Did you try the answer from C# - Fill a combo box with a DataTable
cboxReason.BindingContext = this.BindingContext;
Related
I have a dropdown list. I am getting data from oracle data base as a dataset I want to fill the dropdown list with dataset values(data text field and data value field). Data coming from the database as normal but I cant bind the values with my drop down list. "ds" is the dataset.
ddlDepartment.DataValueField = ds. Tables[0].Rows[0]["DEPARTMENT"].ToString();
ddlDepartment.DataTextField = ds. Tables[0].Rows[0]["DEPARTMENT_NAME"].ToString();
I think you might be grasping this wrong.
The dropdown combo has a simple setting that allows you to "set" WHAT values from the datasource will be used from the data table you "feed" the drop down list.
So, you can have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
So, you can set the two columns used - they are NOT for feeding data to the dropodown.
You can also set the above two columns in code - but LITTLE need exists to do that.
eg:
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "HotelName";
ONCE you set the above, you are now free to query the database, load up say a datatalbe, and then assign that "table" to the Dropdown list.
You do it this way:
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT ID,HotelName, City FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
DropDownList1.DataSource = rstData;
DropDownList1.DataBind();
// add one blank row selection.
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
So, note how the data table has 3 columns, but WHICH of the 3 do you want to use fo for the dropdown? You have two columns - typical the "ID" or "PK" value, and then the 2nd column is a text description.
Now, I am using the SqlProvider (for sql server). You have to replace SqlCommand with the OracleSQLcommand and also the connection. But the data table, and code that fills the dropdown list reamins the same as per above - regardless of what data provider you are using.
So those two settings (DataValueField, DataTextField) are NOT to be feed data, but are ONLY to set which columns to use from the data table. My example had 3 columns, but there could be 20 columns in that table - so those two settings determine which two columns to use. And often you might have a simple drop down to select a color or some such - and thus you ONLY need one column. In that case, set both Value/Text field to the one same column.
I was able to fill the dataset as follows at the page load
`private void filldepartment()
{
UserClass obj = new UserClass();
DataSet ds2 = new DataSet();
ds2.Merge(obj.departments());
ddlDepartment.DataSource = ds2.Tables[0];
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataBind();
}`
and then find the values as follows
ddlDepartment.DataSource = ds;
ddlDepartment.DataBind();
Adjusted version of your code, removing unnecessary operations:
private void FillDepartmentDropDown()
{
UserClass obj = new UserClass();
var dt = obj.GetDepartments();
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataSource = dt;
ddlDepartment.DataBind();
}
And then GetDepartments might look like:
public DataTable GetDepartments(){
using var da = new OracleDataAdapter(
"SELECT department_id, department_name FROM departments ORDER BY NLSSORT(department_name, 'NLS_SORT=GENERIC_M')",
_connstr
);
var dt = new DataTable();
da.Fill(dt);
}
I have two forms, in one I fill DataGridView with some rows, each row has two comboboxes.
I am able to get both value and formatted value from these cells, however when I try to copy all of this data into the next DataGridView that is in different form, I am unable to tell him which item from the ComboBox should be marked as selected.
When I was looking around I found these lines of code (unfortunately they were from 6+ years ago)
dataGridView.Rows[index].Cells[3].Value = ImageFormat.Items[1];
(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = ImageFormat.Items[0];
DataGridViewComboBoxCell comboboxFormat = (DataGridViewComboBoxCell)(dataGridView.Rows[index].Cells[3]);
comboboxFormat.Value = ImageFormat.Items[0];
(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = (dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Items[0];
Unfortunately none of these worked and most if not all threw "DataGridViewComboBoxCell value is not valid" exception
Maybe it's worth to mention that the possible items are binded from database like so:
string stm = "SELECT * FROM colours";
using var cmd = new SQLiteCommand(stm, MainWin.con);
SQLiteDataAdapter rdr = new SQLiteDataAdapter(cmd);
DataTable dataTableColour = new DataTable();
rdr.Fill(dataTableColour);
stm = "SELECT * FROM formats";
using var cmdd = new SQLiteCommand(stm, MainWin.con);
SQLiteDataAdapter reader = new SQLiteDataAdapter(cmdd);
DataTable dataTableFormat = new DataTable();
reader.Fill(dataTableFormat);
ImageFormat.ValueMember = "id";
ImageFormat.DisplayMember = "name";
ImageFormat.DataSource = dataTableFormat;
ColourImage.ValueMember = "id";
ColourImage.DisplayMember = "name";
ColourImage.DataSource = dataTableColour;
Your datagridview should be bound to some datatable (let's say ImageFiles). Set ColourImage/ImageFormat combo's .DataPropertyName property to be the name of the column in the [ImageFiles] datatable that the combo should edit. Don't try to interact with the DGVCombo directly; just interact with the datatable to which the grid is bound
I'm trying to search for a code entered by the user in a sqlite table if it's found add the row to a dataGridView. the problem is that the code I'm using clears the datagrid every time I add a new row.
Here is the code I'm using
DataTable dt = new DataTable();
String insSQL = "select * from Produtos where codigo =" + txtCodigo.Text;
String strConn = #"Data Source=C:\caixa.sqlite";
SQLiteConnection conn = new SQLiteConnection(strConn);
SQLiteDataAdapter da = new SQLiteDataAdapter(insSQL, strConn);
da.Fill(dt);
dataGridViewProdutos.DataSource = dt.DefaultView;
I tried to change the dataGridViewProdutos.datasource to dataGridViewProdutos.Rows.add(dt); them it adds a row but always empty.
I fixed it removing the DataTable dt = new DataTable(); from the loop. I also changed the dt.DefeulView to only dt as sugested by N4TKD and Im seeing no diference so Im using it.
Also thanks for the links it was very helpfull since I was struggling to make my colums fill the dataGridView space.
I have Gridview (gridview1), some TextEdits in the Form and add some Data's to few rows and i stored the gridview1 Data's and textedits to Access Database. In another form i Bind some column to gridview1 and TextEdits to new Gridview (gridview2). Now if i click edit button on any row in the gridview2, I want to get the Data's from Access Database and shown in 1st Form gridview1 and textedits fill automatically recording to Focused Row cell unique value.
Using this code i get value to TextEdits Fields
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb");
OleDbCommand da = new OleDbCommand("select * from invoice_top where invoice_number=" + textEdit5.Text, con);
con.Open();
OleDbDataReader reader = da.ExecuteReader();
while (reader.Read())
{
textEdit12.Text = reader.GetValue(1).ToString();
textEdit13.Text = reader.GetValue(2).ToString();
textEdit4.Text = reader.GetString(3);
dateEdit1.Text = reader.GetValue(8).ToString();
textEdit1.Text = reader.GetValue(5).ToString();
textEdit2.Text = reader.GetValue(6).ToString();
textEdit3.Text = reader.GetValue(7).ToString();
checkEdit1.Checked = reader.GetBoolean(4);
}
con.Close();
I also want to fill gridview Data's ? I tried this bus its not working
gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[2], reader1.GetString(2));
How to set Access Database values to grdiview ?? Please Help me ?
Thanks in Advance.
I think you need to read a tutorial on Data Binding.
The GridControl can be bound to a data source which implements IList<>, IBindingList<> or IQueryable<> simply by setting the GridControl.DataSource property. There is no need to loop through your recordset and set the value for each row/cell individually. Additionally, I would suggest you Data Bind your TextEdit controls (to the EditValue property, NOT the Text property) rather than manually setting them like you are doing above.
This code is VB.NET but the ideea is the same in C#
Dim SIRCON as string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb"
Using con As New OleDbConnection(SIRCON)
con.Open()
Dim strSQL As String = "select * from invoice_top where invoice_number=" + textEdit5.Text
dim dt as new datatable
dt.Load(New OleDbCommand(strSQL, conexiune).ExecuteReader())
conexiune.Close()
GridControl1.datasource = dt
GridControl1.ForceInitialise
End Using
I have a listbox and would like to fill it with data from a database, the two must be linked so if i select a value from the listbox i can work with the entry in the database.
I'm using a disconnected database witch connects though a connection string:
conn = new SqlConnection(Properties.Settings.Default.DBConnectionString)
I have read up on dataset's and think i need to create one and use it as my listbox data source, Then to have the data displayed looking neat i need to set the display name.
Could someone show me how to create a dataset that's connected to my table in my database and then show me how to bind it.
Database is called TagCloudDB and table is called Tag and just listbox1.
This is the code i have so far, but it just fills the listbox with System.Data.DataRowView.
using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString))
{
conn.Open();
SqlDataAdapter daTags
= new SqlDataAdapter("Select * From Tag", conn);
DataSet dsTags = new DataSet("TagCloud");
daTags.FillSchema(dsTags, SchemaType.Source, "Tag");
daTags.Fill(dsTags, "Tag");
daTags.MissingSchemaAction = MissingSchemaAction.AddWithKey;
daTags.Fill(dsTags, "Tag");
DataTable tblTag;
tblTag = dsTags.Tables["Tag"];
dplTags.DataSource = dsTags;
dplTags.DataMember = "Tag";
dplTags.DataBind();
}
I did some thing similar in collage with VB and they have a ValueMember and Displaymember, Whats the equivalent in C#
SqlConnection _connection = new Connection(connectionString)
SqlDataAdapter _adapter = new SqlDataAdapter(_connection, "select * from tag")
DataTable _table = new DataTable()
_adapter.Fill(_table)
_connection.Close();
foreach(DataRow _row in _table.Rows)
{
listbox.AddItem(new Item(_row["column1"], _row["column2"])
}
You don't need to mess with datatables. It automatically binds with the sql query.