I am trying to populate my listbox and can only populate it with System.Data.Datarow 5 times, witch is the amount of entry's i have in my database.
I need my list box to be linked with my Database so that i can use it to select items to make changes to, so don't want to just populate it but rather bind it.
I can't seem to find ValueMember and DisplayMember properties. I think this may be because i'm Programming in webForms.
My Code:
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();
}
You should also specify the DataValueField(ValueMember) and DataTextField(DisplayMember) properties.
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 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;
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.
I have MySQL database with four tables, and I've written form an example binding method. But this solution works well only with one table. If I bind more than one, dataGridViews will be filled with info, but Update and Delete commands work badly.
public void Bind(DataGridView dataGridView, string tableName)
{
string query = "SELECT * FROM " + tableName;
mySqlDataAdapter = new MySqlDataAdapter(query, conn);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataTable = new DataTable();
mySqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView.DataSource = bindingSource;
}
Should I use different mySqlDataAdapter or mySqlCommandBuilder for each new table? I've used different DataTable and BindingSource objects, but when I inserted new row in one table, I had an exception that I left empty field in other table. Any solutions or tips for this problem?
Thanks in advance!
Better late than never I guess...
I have an application that loads different tables into the same DataGridView using Visual Studio 2013. So far it is working!
1. DataTable
You certainly need to create a new one for each different table you want to load, otherwise you can not clear out the old data. You might think that
dataTable.Clear()
would do the trick but no, it leaves the old column headers behind so your new table is loaded to the right of all the old columns :-(. Although interestingly if your new table has a column with the same name as the old it merges them!
2. MySqlAdapter
I currently create a new one for each table, but at the very least your sql query is changing so you need to create a new SelectCommand:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `" + tableName + "`", conn);
sqlAdapter.SelectCommand = cmd;
I've tried this and it seems to work, but actually it is simpler to just create a new MySqlAdapter and performance really isn't an issue at this point!
3. SqlCommandBuilder
Yes you should create a new one because the update and delete commands will be different. I don't use a class variable but create one dynamically (i.e. as a local variable) when I need it.
4. BindingSource
I don't believe you need a new BindingSource, but I haven't used them very much so can't be certain.