DropDownList not working with SqlDataReader - c#

Hi i am trying to get DropDownList to work with SqlDataReader but its not populating the DropDownlist. The TextBox.Text Reader is working though.
Here is the code I am using:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
{
SqlCommand command =
new SqlCommand("SELECT * FROM [datarep].[dbo].[OrderHeader] WHERE [OrderNumber] = '"+OrderNumber+"'", con);
con.Open();
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
TextBox2.Text = (read["CreatedDate"].ToString());
TextBox3.Text = (read["CreatedBy"].ToString());
CompanyStored = (read["CustomerID"].ToString());
TextBox7.Text = (read["Store_Number"].ToString());
DropDownList1.DataTextField = (read["Year"].ToString());
DropDownList1.DataBind();
}
read.Close();
}

Assuming your dropdown is already populated with the list of years, you need to set its value rather than setting its DataTextField - that property is meant for defining the column or property name of the data source for text, not setting the selected value itself.
DropDownList1.SelectedValue = read["Year"].ToString();
If you don't have the dropdown even populated yet, then you have to populate it in advance, using a data source, which is probably a list of years. For example, suppose you want all years between 2000 and 2050, something like this might do the trick:
var dataSource = Enumerable.Range(2000, 51)
.Select(x => new { TheYear = x })
.ToArray();
DropDownList1.DataSource = dataSource;
DropDownList1.DataValueField = "TheYear";
DropDownList1.DataTextField = "TheYear";
DropDownList1.DataBind();
Note that the DataTextField and DataValue field represent the property of the object in the data source.
For something simple like numbers, you can populate the dropdown one at a time as well, rather than using a data source - it's the same result in the end.

SqlDataReader reads your data line by line. If you want to use a DataReader you'll have to add a new list item to your DDL per iteration
Try it like this:
while (read.Read())
{
/*code omitted*/
var item = new ListItem();
item.Text = read["Year"].ToString();
item.Value = read["Year"].ToString();
DropDownList1.Items.Add(item);
}
Further reading and alternative solutions:
What is the right way to populate a DropDownList from a database?

Related

Set SelectedValue in combobox that populated from Data Table in c#?

I have a Combobox in my form. This Combobox is populated with values from a table(Faculty) in the database.
I need to set the SelectedValue of this Combobox based on the record in another table(student). Both tables are in the same database.
I tried to set SelectedValue using the value getting from student table
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
but it didn't work.
So far I was only able to populate the Combobox ,
// --- populate faculty cmb ---
MySqlCommand cmdCmb = new MySqlCommand("SELECT facultyname FROM faculty;", db.getConnection());
db.openConnection(); // open connection
using (var reader = cmdCmb.ExecuteReader())
{
while (reader.Read())
{
cmbfaculty.Items.Add(reader.GetString("facultyname"));
}
}
but unable to set SelectedValue.
string sQuery = "SELECT indexno,faculty FROM student WHERE indexno ='"+selected+"'";
MySqlCommand cmd = new MySqlCommand(sQuery, db.getConnection());
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
txtindex.Text = table.Rows[0][0].ToString();
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
Hoping to fix the issue.
EDIT:
Able to do that by finding the item that exactly matches the specified
string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
Are there any other ways to archieve this.
Able to do that by finding the item that exactly matches the specified string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;

C# Checklistbox Value with Database

My checklist box is generated using a query
query = #"SELECT CONTENT
FROM qBank
GROUP BY CONTENT
ORDER BY MIN(CHAP)";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter dAdap = new OleDbDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdap.Fill(dSet);
for (int i=0; i < dSet.Tables[0].Rows.Count; i++)
{
chkList.Items.Add(dSet.Tables[0].Rows[i][0].ToString());
}
I want to get the values of the checkeditems query the CONTENT/s checked and pass it to the next form. But Im lost on how to do it. I saw using foreach statement, but honestly I cannot come up with the condition.
ListItem item = new ListItem();
item.Text = dSet.Tables[0].Rows[i][0].ToString(); //Text field here
item.Value = dSet.Tables[0].Rows[i][1].ToString(); //value field here
chkList.Items.Add(item);
Try to achieve this, hope you have different text and value fields, if you not have that use same thing into value and text field

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

Unable to get dropdown selected value

I have a gridview that is populated with a dropdown list on each row. The DDL is populated with a number from 1 - how ever many rows there are.
I have a save button to save the value of each DDL for each row using a simple loop but the problem is that the dropdown never returns the selected value, it seems to return something like the row index of the gridview + 1.
This is an example of how I select the values in the rows:
3
7
4
6
5
2
1
When I do the same, this is how they will save:
2
3
4
5
6
7
1
This is my code from the save, just to let you know I have tried selectedvalue, selectedindex, selecteditem and text, they all do the same.
//save the data
foreach (GridViewRow r in gvOrder.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
//get the details from the grid
Label lblED = r.FindControl("lblED") as Label;
DropDownList ddl = r.FindControl("ddlNewO") as DropDownList;
TextBox txt = r.FindControl("txtNewT") as TextBox;
Label ID = r.FindControl("lblID") as Label;
int Order = Convert.ToInt16(ddl.SelectedValue);
string Text = "";
if (txt.Text != "")
{
Text = txt.Text;
}
//save each row to the db
try
{
SqlConnection dbConnection = new SqlConnection();
dbConnection.ConnectionString = GetConnection.GetConnectionString();
SqlCommand dbCommand = new SqlCommand("PL_UserColumns_Save", dbConnection);
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.Add("#PageID", SqlDbType.Int).Value = Convert.ToInt16(constPageID);
dbCommand.Parameters.Add("#UserID", SqlDbType.Int).Value = Convert.ToInt16(strUserID);
dbCommand.Parameters.Add("#Order", SqlDbType.Int).Value = Convert.ToInt16(Order);
dbCommand.Parameters.Add("#ColumnID", SqlDbType.Int).Value = Convert.ToInt16(ID.Text);
dbCommand.Parameters.Add("#ED", SqlDbType.Int).Value = Convert.ToInt16(lblED.Text);
dbCommand.Parameters.Add("#Text", SqlDbType.NVarChar).Value = "'" + Text + "'";
dbConnection.Open();
dbCommand.ExecuteNonQuery();
dbConnection.Close();
}
catch (SqlException ex)
{
ExceptionHandling.SQLException(ex, constPageID, constIsSiteSpecific);
}
}
}
to get the DropDownList selected value you have to use this:
ddl.SelectedItem.Value
You can check Request.Form to get the posted values. Assuming that your drop-down names will increase with each row e.g. ddlNew0, ddlNew1, etc., then you can do this
var value = Request.Form["ddlNew" + rowIndex];
I would do it in two possible ways:
Add a bit of JavaScript to populate a hidden field and then grab and separate the values in the back-end
Add auto-postback on dropdowns and an onClick method. Also pass the item id as argument. Then do the saving bit in the onclick method.
I would prefer the second one.

Why do I get "System.Data.DataRowView" instead of real values in my WinForms Listbox?

Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.
Can anyone see why?
Code:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;
I always have to deal with this problem, even if I set the DisplayMember and ValueMembers of the List Box.
Your current code is correct and should work, if you need access to the current selected item value of any column of your dTable you can get them doing this:
DataRowView drv = (DataRowView)lstNames.SelectedItem;
String valueOfItem = drv["NameAndScore"].ToString();
What I like about getting the entire DataRowView is that if you have more columns you can still access their values and do whatever you need with them.
The following code should work:
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dSet.Tables[0];
If it does not work, please update your question and provide us with some information about the columns and values that are actually returned in dSet.Tables[0].
Set your lstNames.DisplayMember and lstNames.ValueMember fields.
Gets or sets the property to display for this ListControl.
Gets or sets the path of the property to use as the actual value for
the items in the ListControl.
This should solve your problem..
Like I said in the comments, please add lstNames.DataBind() to your code.
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
EDIT:
Can you try this instead:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
myConn .Open();
SqlCommand cmd = new SqlCommand(sqlStr, SQLConnection1);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lstNames.Items.Add(rd[0]);
}
rd.Close();
rd.Dispose();
myConn.Close();
If you want your list box to show values from an specific column of the data source use
lstNames.DataTextField = "SpecialColumnName";
I use :
foreach (DataGridViewRow row in _dataGridView.SelectedRows)
{
var rowObject = row.DataBoundItem as DataRowView;
var array = rowObject.Row.ItemArray;
}
Only the order of the calls is wrong. First set the DataSource and only after that set the display member:
lstNames.DataSource = dTable;
lstNames.DisplayMember = "NameAndScore";
I had the similar problem of picking a single value from a populated Listbox and getting System.Data.DataRowView.
I was able to solve it by casting the selected item to System.Data.DataRowView and then
accessing the Row and ItemArray subclasses:
var si = ListBox1.SelectedItem;
string val = ((System.Data.DataRowView)si).Row.ItemArray[0].ToString();
I know its an old question. Just thought it might be nice to add an update to the answers given already. I was looking for a solution to the same problem. I the realized it is in which order you place these 3 lines of code
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
It should use the datasource first. Then The value member and then the display member
As follow:
lstNames.DataSource = dTable;
lstNames.ValueMember = "NameAndScore";
lstNames.DisplayMember = "NameAndScore";
just make sure you are typing the name of field same as in datasource in other word it is a case sensitive
so :
Me.GridLookUpEdit1.Properties.DisplayMember = "cur_code"
is different than
Me.GridLookUpEdit1.Properties.DisplayMember = "CUR_code"
if you copied the object instead of placing as a new object it will do this. Try deleting the object and putting it back on. I had the same issue and this is what I did. Don't know why it worked, but it did.
Sometimes what might cause it is mis-spelt displaymember variable name.

Categories