How do I assign values to checkboxes from an ArrayList - c#

I hope you're well.
I want to get the data from my Access database and assign each row to a checkbox in a form in c#. So, I have read the data from the database to an arraylist. Now, I do not know how exactly I can assign those values to the checkboxes from the ArrayList.
I thought I could just say:
checkbox1.Text = Cakes(0);
but it is saying that I need a method.
Please assist me.
Here is the code that I have so far.
public partial class Customer : Form
{
private OleDbConnection connection = new OleDbConnection();
public Customer()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=FILE PATH;Persist Security Info=False;";
}
private void Customer_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * Cakes";
List<string> Cakes = new List<string>();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Cakes.Add(reader["Product Name"].ToString());
}
}
checkBox1.Text = Cakes(0);
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}

In the while loop add all the values to the Cakes list, after that assign the list as the CheckBox text, based on the code example (notice the Cakes[0]), also put the connection in a using statement so it's disposed and closed (removed the connection.Close() and moved the reader):
private void Customer_Load(object sender, EventArgs e)
{
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * Cakes";
List<string> Cakes = new List<string>();
using (connection)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Cakes.Add(reader["Product Name"].ToString());
}
}
checkBox1.Text = Cakes[0];
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}

Related

user selection Combobox then to Labels according to database MS Access c#

i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

Show information from MySQL database

I want to pass the information I get from a database to a label. How can I pass the information into a variable.
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
var numero = textBox1.Text;
string connection_string = "datasource=xxx;port=111;username=xxx;password=xxx";
string Query = "select * from xxx.lojass where nome =" + numero;
MySqlConnection conDate = new MySqlConnection(connection_string);
MySqlCommand cmdDate = new MySqlCommand(Query, conDate);
MySqlDataReader myReader;
try
{
conDate.Open();
myReader = cmdDate.ExecuteReader();
MessageBox.Show("Conected");
while (myReader.Read())
{
label1.Text
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Proper coding. Explanation in code comments below
private void button1_Click(object sender, EventArgs e)
{
try
{
const connStr = "datasource=xxx;port=111;username=xxx;password=xxx"; // constant
// Instead of "select *" select particular column(s), it will help with reader columns later
var sql = "select column1 from xxx.lojass where nome = #1"; // you need to parameterize. Never push text box value directly into sql
// important to use "using" to release resources
using (var conn = new MySqlConnection(connStr))
{
using (var cmd = new MySqlCommand(sql, conn))
{
// assuming "nome" is string. If the value is other datatype - convert it
// Better yet - create parameter where you explicitly specify mySql data type
cmd.Parameters.AddWithValue("#1", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader()) // Since single value expected another way doing it - ExecuteScalar
{
// you only fill one single value, so makes sense to use IF, not WHILE
if (reader.Read())
label1.Text = reader["column1"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Load two / several MS Access Table into C# Windows Form

I´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;

C# loading data from MS Access database to listbox

public partial class Form1 : Form
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb;Persist Security Info=True";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
dr.Close();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
}
This is an image of the database:
I added 2 list boxes. Those two should display the data i put in the database but It doesn't. I don't know which is wrong, the path, the code or the database
There is nothing wrong with you code. Check if you are getting any exceptions or pointed to the right database.
Also check if you have assigned the function Form1_Load() to form's load event
I'm not sure what your problem is, but you can change the connectionString by this way:
System.Data.OleDb.OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.OleDbServices = -1;
builder.DataSource = #"C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb";
cn.ConnectionString = builder.ConnectionString;
OleDbServices = -1 can help you.

SQL datareader reading inconsistently

I have the following code in C#-
private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();
if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}
I am getting the value of the variable enqid from a combobox on my Windows form.The contents of the combobox are retrieved from the database. On form load, the combobox displays the first enquiryID retrieved from the database. When I run my program the data reader skips the loop. However if I select a different enquiry in the combobox, the data reader works properly
It seems that you've forgot to associate Command with the Connection:
// SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this
// have SQL readable
cmd.CommandText =
#"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = #prm_Id";
// use parametrized queries
cmd.Parameters.AddWithValue("#prm_Id", enqid);
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}
And never, never after write code alike
catch (Exception)
{
}
which means "just ignore all the errors and continue".

Categories

Resources