Array with different data type c# - c#

I am working with a window form application. I have an array to store a list of checkbox with different data type in it (string and integer). Below code is my checkBox checkBox A to E get the employee name and cheeckBox 1-5 get the employee favorite number.
//Array of Class and secondary Check Box
CheckBox[] myCheckBoxArray = new CheckBox[10];
myCheckBoxArray[0] = checkBoxA;
myCheckBoxArray[1] = checkBoxB;
myCheckBoxArray[2] = checkBoxC;
myCheckBoxArray[3] = checkBoxD;
myCheckBoxArray[4] = checkBoxE;
myCheckBoxArray[5] = checkBox1;
myCheckBoxArray[6] = checkBox2;
myCheckBoxArray[7] = checkBox3;
myCheckBoxArray[8] = checkBox4;
myCheckBoxArray[9] = checkBox5;
After that I am trying to bind the checkbox to my SQL database and have a foreach loop to check if anyone of these checkbox is checked. I am wondering if this is a good way to combine both integer and string array together or should I use a nested foreach loop? Because I am struggling with me SQL statement when I do something like this. For some reason, I get a conversion failed when converting the varchar value 'A' to data type int. I am not sure how I should fix this problem.
foreach(var selectedItems in myCheckBoxArray){
if(selectedItems.Checked){
string q = "SELECT * FROM [tb1] as tb1 LEFT JOIN [tb2] as tb2 ON tb1.id = tb2.id
LEFT JOIN [tb3] as tb3 ON tb1.eId = tb3.eId
WHERE employeeName = '" + selectedItems.Text + //get the name
"' AND empFavorityNumber = '" + selectedItems.Text + "'" //get the integer
}
}
NEW EDITED
CheckBox[] myCheckBoxArray = new CheckBox[5];
myCheckBoxArray[0] = checkBoxA;
myCheckBoxArray[1] = checkBoxB;
myCheckBoxArray[2] = checkBoxC;
myCheckBoxArray[3] = checkBoxD;
myCheckBoxArray[4] = checkBoxE;
CheckBox[] mySecCheckBoxArray = new CheckBox[5];
mySecCheckBoxArray[0] = checkBox1;
mySecCheckBoxArray[1] = checkBox2;
mySecCheckBoxArray[2] = checkBox3;
mySecCheckBoxArray[3] = checkBox4;
mySecCheckBoxArray[4] = checkBox5;
foreach(var selectedItems in myCheckBoxArray) {
foreach (var secondselectedItemsin in mySecondCheckBoxArray)
{
if (checkedItems.Checked)
{
string q = "SELECT * FROM [tb1] as tb1 LEFT JOIN [tb2] as tb2 ON tb1.id = tb2.id
LEFT JOIN [tb3] as tb3 ON tb1.eId = tb3.eId
WHERE employeeName = '" + selectedItems.Text + //get the name
"' AND empFavorityNumber = '" + secondselectedItems.Text + "'" //get the integer
}
}
}

Related

How to add second DataSource to existing DataGridView in windows forms

I need to add second DataSource to DataGridView which already has one DataSource, or if that isn't possible maybe I can dynamically add new columns with rows from the second DataSource to the DataGridView filled with the first DataSource. Please if someone can give an example and explanation of how to manage that. Thanks in advance.
More details:
the first DataSource returns 4 columns, and the second DataSource returns only 2 columns but both DataSources returns equal numbers of rows in a columns. So if the first DataSource returns 4 rows the second DataSource will also return 4 rows.
I managed to bound the first DataSource to the DataGridView but I don't know how to add second. Both DataSources returns data form the same mySql tables in a separate List but with a different data values.
dataGridViewMojaDjeca - Name of the DataGridView to which I need to add both DataSources, DohvatiOcjene - method which returns the list which is the first DataSource saved in a List called "listaOcjenaDjeteta", DohvatiProfesore2 method which returns the list which is the second DataSource which I haven't saved nowhere because I don't know how to add it to the DataGridView DataSource which already contains data from the first DataSource.
void PrikaziPodatkeDjeteta(object sender, EventArgs e)
{
Ocjene ocjeneDjeteta = new Ocjene();
ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
List<Ocjene> listaOcjenaDjeteta = ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta; // here I need to add second DataSource!***
DohvatiPodatkeDjeteta(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
lblImeIPrezime.Text = djeca.imeDjeteta + " " + djeca.prezimeDjeteta;
lblKorisnickoIme.Text = djeca.korImeDjeteta;
dataGridViewMojaDjeca.AutoResizeColumns();
}
public List<Ocjene> DohvatiOcjene(int korisnik)
{
List<Ocjene> listaOcjena = new List<Ocjene>();
//string sqlUpit = "SELECT * FROM Ocjenjivanje WHERE id_ucenik = '" + korisnik + "';";
string sqlUpit = "SELECT Ocjenjivanje.vrijeme, Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora, Predmet.naziv AS nazivPredmeta, Ocjenjivanje.ocjena, Ocjenjivanje.napomena FROM Korisnik, Predmet, Ocjenjivanje, Profesor_predaje, Razred_ucenik, Profesor_predaje_predmet_razredu WHERE Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis and Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis and Profesor_predaje.id_predmet = Predmet.id and Profesor_predaje_predmet_razredu.id_razred_ucenik = Razred_ucenik.id_zapis and Razred_ucenik.id_ucenik = Korisnik.id and Korisnik.id = '" + korisnik + "';";
DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
while (dr.Read())
{
Ocjene o = new Ocjene(dr);
listaOcjena.Add(o);
}
dr.Close();
idZapisa = 0;
return listaOcjena;
}
public List<Ocjene> DohvatiProfesore2()
{
List<Ocjene> imeProfesora = new List<Ocjene>();
//prezimeProfesora = "", imeIprezimeProfesora = "";
if (idZapisa != 0)
{
//string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id GROUP BY Korisnik.prezime, Korisnik.ime;";
string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id;";
DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
while (dr.Read())
{
Ocjene o = new Ocjene(dr);
imeProfesora.Add(o);
//prezimeProfesora = dr["prezimeProfesora"].ToString();
}
dr.Close();
//imeIprezimeProfesora = imeProfesora + " " + prezimeProfesora;
}
else
{
//imeIprezimeProfesora = "";
}
return imeProfesora;
}
You can declare List and add your two result List in it, and after it set it as datasource and refresh datagrid like this:
List<Ocjene> listaOcjenaDjeteta = new List<Ocjene>();
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta));// Add first List
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiProfesore2());// Add second List
dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta;
dataGridViewMojaDjeca.Refresh();

code optimisation : list loop and query c# sql server compact edition

the code here is for checking is there any interaction between added drugs in a dataGridView ( Productgridview )
front end : C# with VS2012 .Net 4.0
back end : sql server compact edition 4.0
the schema for database :
table product : productId ; name
table product_druginteractionclass : productId ;
druginteractionclassId
table interaction : interactionId ; druginteractionclassId1 ;
druginteractionclassId2 ; riskcomment
table druginteractionclass : druginteractionclassId ; name
many products can have same drug interaction class number
the approach is :
looping throw Productgridview to retrieve the productid based on name
and select druginteractionclassId based on productid then put the result in another dataGridView (listclassification)
create 2 lists from data in column druginteractionclassId from dataGridView (listclassification) /// a minor problem is here it show interaction between same drug because the lists hold same all druginterctionclass number and double iterating throw them to test combination interactions /// how to create separate lists programmatically while i can not know how much drugs will be added ?
looping throw 2 lists and select interactions based on combinations and join the result with a drug interaction class name
is it possible to create lists dynamically and looping throw them to
do combinations while not know how much lists till run time ?
i think of also looping inside the interaction gridview and check if a products is repeated if no remove the inappropriate interaction .
may be all off that can be summarized in a one query , how to wrote
one (that kind of select of select of select)?
actually i am pharmacy student ( i just like to code and do not do it well, i do not even complete any c# book just around 600 page between c# / sql / ado.net so excuse me )
var ds2 = new DataSet();
for (var i = 0; i < Productgridview.Rows.Count; i++)
{
var listclasse = Productgridview.Rows[i].Cells["Productid"].Value.ToString();
var datadrug2 = "SELECT * FROM product_druginteractionclass" +
" where productId = '" +
listclasse + "'"; // listclasse is the list of manually added drugClass
var connection1 = new SqlCeConnection(connectionString);
var dataadapter1 = new SqlCeDataAdapter(datadrug2, connection1);
//var ds = new DataSet();
connection1.Open();
dataadapter1.Fill(ds2, "product_druginteractionclass");
connection1.Close();
}
listclassification.DataSource = ds2;
listclassification.DataMember = "product_druginteractionclass";
/////////////// put the druginteractionclass into 2 lists
var list1 = new List<string>();
var list2 = new List<string>();
foreach (DataGridViewRow item in listclassification.Rows)
if ((item.Cells.Count >= 2) && //atleast two columns
(item.Cells[1].Value != null)) //value is not null
{
list1.Add(item.Cells[1].Value.ToString());
list2.Add(item.Cells[1].Value.ToString());
}
//for (var i = 0; i <= list.Count - 1; i++)
//{
// // MessageBox.Show(list[i].ToString());
//}
//////////// select interaction based on druginteractionclass
var ds = new DataSet();
for (var i = 0; i <= list1.Count - 1; i++)
for (var j = 0; j <= list2.Count - 1; j++)
{
var value = list1[i];
var value1 = list2[j];
var datadrug3 = "SELECT u1.name, u2.name , m.* " +
"FROM druginteractionclass u1 " +
"left outer JOIN interaction m" +
" ON u1.druginteractionclassId = m.druginteractionclassId1 " +
"left outer JOIN druginteractionclass u2 " +
"ON u2.druginteractionclassId = m.druginteractionclassId2" +
" where m.druginteractionclassId1 = '" + value +
"' and m.druginteractionclassId2 ='" + value1 + "'" +
"Order by m.severity ";
var connection = new SqlCeConnection(connectionString);
var dataadapter = new SqlCeDataAdapter(datadrug3, connection);
connection.Open();
dataadapter.Fill(ds, "interaction");
connection.Close();
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "interaction";
/////// remove duplicated interactions
for (var currentRow = 0; currentRow < dataGridView1.Rows.Count - 1; currentRow++)
{
var rowToCompare = dataGridView1.Rows[currentRow];
for (var otherRow = currentRow + 1; otherRow < dataGridView1.Rows.Count; otherRow++)
{
var row = dataGridView1.Rows[otherRow];
var duplicateRow = true;
for (var cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
if (!rowToCompare.Cells[2].Value.Equals(row.Cells[2].Value))
{
duplicateRow = false;
break;
}
if (duplicateRow)
{
dataGridView1.Rows.Remove(row);
otherRow--;
}
}
}
var datadrug3 =
#" SELECT m.interactionId , u1.name , n.name , u2.name,n2.name , m.riskComment , m.precautionComment , m.severity
FROM druginteractionclass u1
left outer JOIN interaction m
ON u1.druginteractionclassId = m.druginteractionclassId1
left outer JOIN druginteractionclass u2
ON u2.druginteractionclassId = m.druginteractionclassId2
left outer join product_druginteractionclass p1
ON p1.druginteractionclassId = m.druginteractionclassId1
left outer JOIN product_druginteractionclass p2
ON p2.druginteractionclassId = m.druginteractionclassId2
left outer join product n
ON n.productId= p1.productId
left outer join product n2
ON n2.productId= p2.productId
where n.productId = #value and n2.productId = #value1 ";
var connection = new SQLiteConnection(connectionString3);
var com = new SQLiteCommand(datadrug3, connection);
com.Parameters.AddWithValue("#value", value);
com.Parameters.AddWithValue("#value1",value1 );
var dataadapter = new SQLiteDataAdapter(com);
connection.Open();
dataadapter.Fill(ds, "interaction");
connection.Close();

c# multiple dropdowns

Table i need to sort
So i got this 5 drop downs i need to use for sorting output from sql
Now i use
DropDownList_Instruktorer.Items.Insert(0, new ListItem("Vælg Instruktør", "*"));
For the Default Value, and i was thinking this will do the job. But
cmd.Parameters.addwithvalue
enter the value into value obviously instead of use * to show all results like it normally does in sql
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE fk_in_id = #Instruktor AND
fk_st_id = #Stilart AND
fk_ag_id = #Aldersgruppe AND
fk_ni_id = #Niveau AND
fk_ht_id = #Tid", conn);
cmd.Parameters.AddWithValue("#Instruktor", DropDownList_Instruktorer.SelectedValue);
cmd.Parameters.AddWithValue("#Stilart", DropDownList_Stilart.SelectedValue);
cmd.Parameters.AddWithValue("#Aldersgruppe", DropDownList_Aldersgrupper.SelectedValue);
cmd.Parameters.AddWithValue("#Niveau", DropDownList_Niveauer.SelectedValue);
cmd.Parameters.AddWithValue("#Tid", DropDownList_Tider.SelectedValue);
Here is my sql, Any idea how i can i get it to work without writing 25 if statements?
Why not use a string in place of the AddWithValue, eg:
string instructorStr = "";
string stilartStr = "";
...
if (DropDownList_Instruktorer.SelectedValue != "*")
{
instructorStr = "fk_in_id = " + DropDownList_Instruktorer.SelectedValue + " AND";
}
if (DropDownList_Stilart.SelectedValue != "*")
{
stilartStr = "fk_st_id = " + DropDownList_Stilart.SelectedValue + " AND";
}
...
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE " +
instructorStr +
stilartStr +
...
+ " 1 = 1", conn);
Then you have the option to do all sorts of stuff with the individual variables, including ORDER BY
Using Stringbuilder would be cleaner but it's easier to show it this way.

c# how to build a dynamic query in the where condition

This is my query
SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK)
WHERE MPRO.Estado0154 = 'QUEUED'
AND F1IdWI02140154<>'VOICEMAIL'
AND F1Camp02930154 = 'Support'
please notice that i have AND F1Camp02930154 = 'Support'
Now I have a list like this:
List<string> compaines = new List<string>();
the values in this list should be in this conidtion AND F1Camp02930154 = 'Support'
for example if the list is empty, i will get an empty result, but if the list has just one value which is Support the query will be
AND F1Camp02930154 = 'Support'
but if the list has two vaules which are Support and Sales then the query will be
AND F1Camp02930154 = 'Support' and `Sales`
how to do that please in c#
where I already have this:
string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL'";
Update 1
After # Gordon Linoff comment
I tried this:
List<string> compaines = new List<string>();
string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL' AND F1Camp02930154 IN (";
for (int i = 0; i < compaines.Count(); i++) {
queryString += "'" + compaines[i] + "'";
}
queryString += ")";
You can use String.Join() to construct IN () clause, for example :
var companies = new List<string>() { "Support", "Sales" };
string inClause = String.Format(" IN ('{0}')", String.Join("', '", companies));
Console.WriteLine("AND F1Camp02930154" + inClause);
//output :
//AND F1Camp02930154 IN ('Support', 'Sales')

Sql runs but doesn't show any content in calendar control

I have an sql select script that will execute and shows that there is data being selected when it is run. The problem I am having is trying to get that data to show in my calendar control. I wanted to change the calender by what department the user was from that logged in. Right now there is nothing showing and it will not show any data unless I hard code a department in it.
I am working with c# asp.net.
here is what I am doing to try and get the data
private DataSet GetData()
{
var CurrUser = "a73 ";
var UsrDepartment = "60 ";
Account.Login uusr = new Account.Login();
CurrUser = uusr.User.Identity.Name.ToString().ToUpper();
ConnectionStringSettingsCollection cssc = ConfigurationManager.ConnectionStrings;
var sql = "select (substring(status, 1,1)) AS stat1, lastname, firstname, ldate, edate,depdivid, requestid from TIME.employee E inner join TIME.request T on E.EMPID = T.empid where E.depdivid = #UsrDepartment ";
using (iDB2Connection conn = new iDB2Connection(GetConnectionString()))
{
conn.Open();
using (iDB2Command cmd = new iDB2Command(sql, conn))
{
cmd.DeriveParameters();
using (iDB2DataAdapter da = new iDB2DataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
}
I fill the calendar with this :
DataSet ds = GetData();
foreach (DataRow row in ds.Tables[0].Rows)
{
//need to fill from first to last date
string scheduledDate = Convert.ToDateTime(row["ldate"]).ToShortDateString();
string endDate = Convert.ToDateTime(row["edate"]).ToShortDateString();
e.Cell.Width = 120;
e.Cell.Height = 100;
Int32 start = 0;
Int32 end = 0;
start = string.CompareOrdinal(scheduledDate, s);
end = string.CompareOrdinal(endDate, s);
if ((start <= 0) & (end >= 0) & (!e.Day.IsWeekend))
{
HyperLink lb = new HyperLink();
lb.Text = link + (Int64)row["requestid"] + "' >" + row["lastname"] + "</a>" as String + "(" + row["stat1"] + ")" as String + "<br />";
//code to change color of button
if (scheduledDate == endDate)
{
lb.CssClass = "changecolor";
}
e.Cell.Controls.Add(lb);
}
}
This way will show no links in my calendar, but if I make the department have a value(which is not what I wanted) it will show the links.
I think you need a line like this
cmd.Parameters["#UsrDepartment"].Value = myDept

Categories

Resources