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);
}
Related
I am using mysql database with my .net application. I have a column animal_reservatory. I am trying to fetch the column values to the the drop down. I am not able to get it working.
<asp:DropDownList ID="DropDownList1"
runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Code:
if (!IsPostBack)
{
string scon = "SERVER=localhost;DATABASE=animal_adoption_site;UID=root;";
MySqlConnection con = new MySqlConnection(scon);
String s = "select * from animal_details";
MySqlDataAdapter dat = new MySqlDataAdapter(s, con);
DataSet ds = new DataSet();
DropDownList1.Items.Clear();
while (ds.Read())
{
DropDownList1.Items.Add(new ListItem(ds[0].ToString(), ds[0].ToString()));
}
con.Close();
}
I am getting
Cannot apply indexing with [] to an expression of type 'System.Data.DataSet'
How can I solve this?
The error is telling you that you can't get the first element of a DataSet like that.
What would you expect this to return?
yourDataSet[0].ToString()
If you wanted the first DataTable, you might've meant to try this:
yourDataSet.Tables[0].ToString()
But calling ToString() on a DataTable doesn't make sense either.
Instead of filling the Items collection one record at a time, just assign the entire result set at once to the DataSource property. (Also, you never actually retrieved the results, as Soner pointed out.)
using (var dat = new MySqlDataAdapter(s, con))
{
var dt = new DataTable();
dat.Fill(dt); // retrieve records
DropDownList1.DataSource = dt;
}
I'm not sure, but you may need to set the DataTextField and DataValueField values on the DropDownList as well, based on the name of the column in the DataTable.
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 want to create a for loop in which i want to write a query which updates the the value of each row in database. the rows are present in the datagridview as well as in the database. the aim is when the changes are made in datagridview so using a button the change are also applied in the database table too. in each row the barcode and its quantity is different. if the changes are made in all the rows in datagridview so it is also to be applied in database using button and also please help with the parameters.
here is the query which should be considered in the for loop:
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
consider barcode as column1 and item_quantity as column2.
so far to create a for loop i have tried this but getting error in the for loops:
for (int i = 0; dataGridView2.Rows.Count; i++) //getting error here
{
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
cmd2.Parameters.AddWithValue("#barcode", dataGridView2.Rows[i].Cells[1].Value.ToString());
cmd2.Parameters.AddWithValue("#qty", dataGridView2.Rows[i].Cells[1].Value.ToString());
}
you should call cmd2.ExecuteNonQuery(); in your loop ... otherwise no sql commands will be executed
to get a better solution you should move to creation of cmd2 before the loop. also add the parameters there (without assigning values) ... inside the loop just assign the values and call ExecuteNonQuery.
maybe the best solution would be to use databinding and a SqlDataAdapter with assigned UpdateCommand.
just saw that there probably is an error in your code ... you use the value from Cell[1] for both of your parameters ...
example:
first create a DataTable ... var dt = new DataTable();
then add the columns you want in your grid to the DataTable ... dt.Columns.Add("xyz");
then attach the DataTable to your grid: dataGridView2.DataSource = dt;
now you should be able to edit the contents of column "xyz". to write the values to the database you create a SqlDataAdapter ... var adp = new SqlDataAdapter();
then set adp.InsertCommand = new SqlCommand(...) and adp.UpdateCommand = new SqlCommand(...)
now you can call adp.Update(); and all the values from your grid are written to db ... for newly added rows the InsertCommand is invoked and for edited rows the UpdateCommand is invoked.
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 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.