C# Checklistbox Value with Database - c#

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

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

How to show database table data into labels text with loop in c# windows form

I'm facing a problem to show database data into labels. I have a database table name is EMP, EMP has 5 columns, I want all EMP data into labels using a loop. please see the image below for better understanding.
Image:
I write blow code for that but this code the only one row of database table, how I get all rows in labels. Please help...
using (SQLiteConnection conn = new SQLiteConnection(Connection.Conn()))
{
string CommandText = "SELECT * FROM EMP";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
conn.Open();
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
label1.Text = dr["EmpCode"].ToString();
label2.Text = dr["EmpName"].ToString();
label3.Text = dr["EmpCity"].ToString();
label4.Text = dr["EmpState"].ToString();
}
}
}
Please help me to find the way of showing all data into labels using loop, any code or link will help.
You could do something like this for every label
label1.Text += dr["EmpCode"].ToString() + "<br />";
Or better you should look at datagridview http://csharp.net-informations.com/datagridview/csharp-datagridview-tutorial.htm
I think too that it would be better

DropDownList not working with SqlDataReader

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?

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.

C# SQL SUM value to a label

I currently have a DataGridView which displays all the item. I would like to sum all the prices in the price column and then reflect the total in a label, 'TotalValueLabel'. What's wrong with my statement?
string query = "SELECT SUM (Price) FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable source = new DataTable();
dAdapter.Fill(source);
TotalValueLabel.Text = source.ToString();
Your source is a DataTable so "source.ToString()" will not give you your result,
Try "source.Rows[0][0].ToString();".
DataTable object contains a list of DataRow objects which hold values for each row of your query result.
In your case however you might not need this. If you are looking for a single value you should use IDbCommand and call ExecuteScalar(). This will return the first value of the first row of your results.
Also try calling Dispose() on objects that implement IDisposable (like dbadapter, command, connection).
string query = "SELECT SUM (Price) FROM Bill";
using (System.Data.IDbCommand command = new System.Data.OleDb.OleDbCommand(query, DBconn))
{
object result = command.ExecuteScalar();
TotalValueLabel.Text = Convert.ToString(result);
}
DataTable is overkill for single value retrieval, besides your not even accessing the value correctly, better way is to use execute scalar:
var query = "SELECT SUM (Price) FROM Bill";
using (var cmd = new OleDbCommand(query, DBcon))
{
TotalValueLabel.Text = cmd.ExecuteScalar().ToString();
}

Categories