How can I put the values retrieved from a query that contains ONE COLUMN and MULTIPLE ROWS to textboxes. What i mean is txtBox1 will have the value of the first row, txtBox2 will have the value of the second row and so on. What I know is how to retrieve values of each column but not rows.
Perhaps:
List<TextBox> allTextBoxes = this.Controls.OfType<TextBox>().ToList();
int current = -1;
using (var con = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
using (var cmd = new MySqlCommand("SELECT ColumnName FROM dbo.TableName", con))
{
con.Open();
using (var rd = cmd.ExecuteReader())
{
while (rd.Read() && ++current < allTextBoxes.Count)
{
allTextBoxes[current].Text = rd.GetString(0);
}
}
}
}
replace this.Controls with the container control that contains all of your TextBoxes.
Related
If I have the following table:
canAssign
------------
1
Is there a way to add the column header text (e.g., canAssign, etc.) to the CheckedListBox as the labels that a user can check?
All answers I've found list the value as the labels, like this:
☐ 1
Instead of this:
☐ canAssign
For Example Only, If I'm using the following to list whatever value is in the canAssign column, how could I change this to list the 'canAssign' column header text?
string myString = "SELECT canAssign FROM Permissions";
using (SqlConnection myConn = new SqlConnection(globalConnectionString))
{
try {
myConn.Open();
using (SqlCommand myComm = new SqlCommand(myString, myConn))
{
SqlDataReader myReader = myComm.ExecuteReader();
while (myReader.Read()) {
checkedListBox1.Items.Add(myReader["canAssign"]);
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
Assuming the SQL query in your code snippet is to get the permissions of a specific user and display them in a CheckedListBox using the same fields names from the database.
If that sounds right, read the entry, loop to get the fields names and values through the SqlDataReader.GetName and SqlDataReader.GetBoolean methods respectively.
//For example...
var myString = "SELECT * FROM Permissions WHERE UserId = ....";
try
{
using (SqlConnection myConn = new SqlConnection(globalConnectionString))
using (SqlCommand myComm = new SqlCommand(myString, myConn))
{
myConn.Open();
using (var myReader = myComm.ExecuteReader())
if (myReader.Read())
for (var i = 0; i < myReader.FieldCount; i++)
checkedListBox1.Items.Add(myReader.GetName(i), myReader.GetBoolean(i));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
In this case I think you'd like to have custom objects in CheckedListBox.Items collection and use CheckedListBox.DisplayMember property with CheckedListBox.ValueMember
DisplayMember
Gets or sets a string that specifies a property of the objects
contained in the list box whose contents you want to display.
ValueMember
Gets or sets a string that specifies the property of the data source
from which to draw the value.
Example
public class ListBoxItem
{
public string Text { get; set; }
public string Value { get; set; }
}
checkedListBox.DisplayMember = "Text";
checkedListBox.ValueMember = "Value";
...create connection and create command logic...
command.CommandText = "SELECT * FROM Permissions";
var reader = command.ExecuteReader();
while (reader.Read()) {
// of course it would be better to cache that and go straight by indexes
for(int i = 0; i < reader.FieldCount; i++) {
var columnName = reader.GetName(i);
// some logic to humanize values like 'canDownload' to 'Can Download'
var label = getLabelFor(columnName);
var value = reader.GetBoolean(i);
checkedListBox.Items.Insert(0, new ListBoxItem(label , value));
}
}
What is the syntax for iterating through a column and changing the values to each button as it iterates?
Example : I have an SQL table with a column named OK with values (0 or 1) and 20 buttons on a form, each button corresponds to a row (button 1 to row 1, button 2 to row 2...etc). I want to iterate through all 20 rows in my dataset and for each row to assign 0 or 1 to its corresponding button (as in button text)
EDIT : I didnt try anything yet cause i dont know exactly how, i know you can iterate through the rows with
Foreach (DataRow drow in table.Rows)
{
foreach(Button X in this.Controls
{
// It was my idea but it clearly doesnt work
}
}
//Sample for MySqlDB
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
private List<string> NumberfromDb = new List<string>();
private int SingleValue = -1;
string QueryGetListUsers = "Select <tablename>.<Columname> From <tablename>;";
cmd = new MySqlCommand(Query, m_mySqlConnection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
SingleValue = rdr.GetInt32("OK").ToString();
NumberfromDb.Items.Add(SingleValue);
}
Now you have the Value in the List Just pass it in the "For" loop and assign it to the Button
eg:
btn1.Text = NumberfromDb[i].ToString();
I am new in WPF. I am trying to load the values from database to fill in CheckedListBox. Based on a condition, some items must be set to checked while loading in checkedlistbox.
How to do this? I have tried the code below, items are loaded in CheckedListBox, but are not checked.
Below is values loaded to checked listbox
public void fillcheck()
{
con = new SqlConnection(connectionstring);
con.Open();
string comboquery = "SELECT [Machine] FROM Department Where active='True'";
SqlCommand cmd = new SqlCommand(comboquery, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string fil1 = rdr.GetString(0);
Checkedlistbox1.Items.Add(fil1);
}
rdr.Close();
}
int departmentID=60//for just refer
Object[] jobs = CheckedlistBox1.Items.Cast<Object>().ToArray();
foreach (Object obj in jobs)
{
string query = "SELECT [Machine] FROM Department Where ID='" + departmentID+ "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string mac = rdr.GetString(0);//Here i get two values(XRAY,CT)but finally shown CT only be checked,so how to do both checked
if (mac == obj.ToString())
{
int indexx = CheckedlistBox1.Items.IndexOf(mac);
if (indexx >= 0)
{
CheckedlistBox1.SetItemChecked(indexx, true);
}
}
}
rdr.Close();
}
You need to transfer your SqlDataReader rdr content to a DataTable. That will help you get a DataTable object containing multiple rows like you have mentioned.
Now for the next step, you can apply a foreach on that DataTable object to iterate over all its rows like this :
foreach(DataRow dr in dt.Rows)
{
if(yourCondition)
{
//set isChecked = true for the checkbox.
}
}
UPDATE :
Try modifying your while loop like this :
while (rdr.Read())
{
string mac = rdr.GetString(0);
ListItem li = new ListItem();
li.Value = "yourBindedValue";// some value from database column
li.Text = "yourBindedText";// use mac if its text.
int index = Checkedlistbox1.Items.IndexOf(li);
if (index >= 0)
{
Checkedlistbox1.SetItemChecked(index, true);
}
}
I have tested this and it works. You just have to pass the Text and Value of the CheckBoxListItem that you are trying to find in the li object and you can get the index if it exists. Make sure you pass both the attributes.
You should have used code-
foreach (int indexChecked in chlstBox.Items)
instead of
foreach (int indexChecked in chlstBox.CheckedIndices)
At start you have 0 selected items and thats why your outer for loop is not working..
EDIT-
Basic Logic is also incorrect.
You should loop through dataset, find the string in checkboxlist and then check it. So, outer foreach loop is not required. Also, make sure that you are using correct checkboxlist variable. In for loop you are using chlstBox
and while searching you are using Checkedlistbox1 ....
i am working on visual studio 2012 c# ...
i inserted values into the combox ...i took them from database...I WANT TO KNOW HOW CAN I ADD AN ITEM TO THE COMBOBOX ...ill show u the code below:
Here this function to fill the combobox with names taken from a table in database containig name and id:
List<Lookup> fillCombo(string query, string column)
{
List<Lookup> lookups = new List<Lookup>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Lookup lookupobject = new Lookup();
lookupobject.ID = Convert.ToInt32(reader["ID"]);
//if (reader["Name"] != DBNull.Value)
lookupobject.Name = reader[column].ToString();
lookups.Add(lookupobject);
}
conn.Close();
}
return lookups;
}
then i call this function as follows:
lookups = fillCombo("select id,name from LookupDetails where LOOKUPID = (select id from Lookup where Name = 'users')", "name");
comboBox2.DataSource = lookups;
comboBox2.DisplayMember = "name";
ComboxBox Items collection cannot be modified when the DataSource property is set.
You got the options of either modifying the List<Lookup> or by adding items into combox by iterating over the List<Lookup>.
Here is option to add items in combobox using foreach loop and insert item at 0 index of comboxbox:
lookups = fillCombo(#"select id,name from LookupDetails where LOOKUPID =
(select id from Lookup where Name = 'users')", "name");
foreach(var obj in lookups)
comboBox2.Items.Add(obj);
comboBox2.DisplayMember = "Name";
comboBox2.Items.Insert(0, "");
Note: In the code mentioned in the question, SqlDataReader was never closed, I have modified it by including using statement. You don't have to close SqlDataReader or SqlConnection when you write these in using block:
List<Lookup> fillCombo(string query, string column)
{
List<Lookup> lookups = new List<Lookup>();
string sConstring = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstring))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Lookup lookupobject = new Lookup();
lookupobject.ID = Convert.ToInt32(reader["ID"]);
//if (reader["Name"] != DBNull.Value)
lookupobject.Name = reader[column].ToString();
lookups.Add(lookupobject);
}
}
}
return lookups;
}
Im wondering how to make my checkboxes in column[3]in dtg_ksluzby checked when the value is in the DB.
klisluz(table where I get the data from) contains columns, id, subkey(which is = vyberradek), text, pocet
This is code for inserting into db.
foreach (DataGridViewRow row in dtg_ksluzby.Rows)
{
if (Convert.ToBoolean(row.Cells[3].Value) == true)
{
SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz(text,pocet,akce,subkey) values(#val1,#val2,#val3,#val4) ", spojeni);
prikaz2.Parameters.AddWithValue("#val1", row.Cells["text"].Value);
prikaz2.Parameters.AddWithValue("#val2", row.Cells["pocet"].Value);
prikaz2.Parameters.AddWithValue("#val3", row.Cells["akce"].Value);
prikaz2.Parameters.AddWithValue("#val4", max + 1);
spojeni.Open();
prikaz2.ExecuteNonQuery();
spojeni.Close();
}
}
Now I would like to check the checkbox when the item is inserted in DB.
Would someone propose me a clue please?
I think I can algorithm this isssue, but I have no idea how can I turn it into the code I thought I can do it somehoe like this :
SqlCommand novyprikaz3 = new SqlCommand("SELECT * FROM klient WHERE ID_K=" + vyberradek, spojeni); //vyberradek selects row ID
spojeni.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
If text in (row where ID_K=number which comes from vyberradek) is in dtg_ksluzby then check the checkbox in the same row
}
I would like to use this for USER to know which columns did he selected before when he is editing
Thank so much in advance.
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT * FROM klient WHERE ID_K=" + vyberradek, spojeni))
{
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.HasRows)
{
row.Cells[3].Value = true;
}
}
}
You have to change vyberradek accordingly to row content.
Try to count it and use ExecuteScalar as below
SqlCommand novyprikaz3 = new SqlCommand("SELECT count(1) FROM klient WHERE ID_K=" + vyberradek, spojeni); //vyberradek selects row ID
spojeni.Open();
Int32 cnt = (Int32) novyprikaz.ExecuteScalar();
If cnt is more than 0 the items exists.