i write a program about customer registiriation. customers inf. saved the txt files. and their depts are saved access database. i want to sort depts small to large . i can sorting depts actually but , i wanna sort depts with ıd s of cutomers. how can i do?
private void button2_Click(object sender, EventArgs e)
{
//listBox3.Items.Clear();
OleDbCommand komut = new OleDbCommand();
conn.Open();
OleDbCommand cmd = new OleDbCommand(" SELECT RemainingDept FROM Dept_Tbl ", conn);
OleDbDataReader dr = cmd.ExecuteReader();
List<string> liste = new List<string>();
while ((dr.Read()))
{
liste.Add(dr["RemainingDept"].ToString());
}
string[] A = liste.ToArray();
int[] B;
B = Array.ConvertAll<string, int>(A, int.Parse);
int tmp;
for (int i = 0; i <B.Length ; i++)
{
for (int j=B.Length-1; j>i; j--)
{
if (B[j - 1] > B[j])
{
tmp = B[j - 1];
B[j - 1] = B[j];
B[j] = tmp;
}
}
}
listBox3.Items.Clear();
for (int i = 0; i < B.Length; i++)
{
listBox3.Items.Add( B[i].ToString());
}
conn.Close();
}
}
}
Example:
My listbox like this code:
30
40
70
I wanna see listbox like:
2 30
1 40
3 70
Use this. It'll sort the data and concatenate the two fields together. Convert it to the list, and display. Skip the custom sorting.
OleDbCommand cmd = new OleDbCommand(" SELECT ID || ' ' || RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);
Change your query to SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept DESC.
Get rid of the sorting code
Change the read line to: liste.Add(dr["ID"] + " " + dr["RemainingDept"]);
1. Class approach:
public class Department
{
public int ID { get; set; }
public int RemainingDept { get; set; }
}
private void button2_Click(object sender, EventArgs e)
{
List<Department> liste = new List<Department>();
OleDbCommand cmd = new OleDbCommand("SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var dept = new Department()
{
ID = Convert.ToInt32(dr["ID"]),
RemainingDept = Convert.ToInt32(dr["RemainingDept"]);
};
liste.Add(dept);
}
foreach(var nItem in liste)
{
listBox3.Items.Add(nItem.ID + " " + nItem.RemainingDept);
}
}
2. Class-less approach:
Same result with much less code.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("SELECT ID, RemainingDept FROM Dept_Tbl ORDER BY RemainingDept", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
listBox3.Items.Add(dr["ID"] + " " + dr["RemainingDept"]);
}
Related
I want to create the attached task scheduler using asp.net and C#.
In SQL Server I have a table with these columns:
InstituteId, InstituteName, Address,
CareerDay2017 (date), CareerDay2018 (date), CareerDay2019 (date)
Dropdown list has values 2017, 2018, 2019. A button should be next to the dropdownlist.
When we select the year from dropdown list and click the button particular data should be retrieved and displayed as the image.
The career day details should be retrieved and colored the particular cell.
This is what I have tried, but it is incorrect. Hope you have taken my idea and help me.
SqlConnection con = new SqlConnection(#"Data Source=NAWODA;Initial Catalog=InternsDB;Integrated Security=True");
SqlCommand cmd;
SqlDataReader sdr,sdr1, sdr2;
String query;
DateTime current = DateTime.Now;
String dateColumn;
StringBuilder table = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
searchDetailPanel.Visible = false;
searchTaskPanel.Visible = false;
if (!Page.IsPostBack)
{
con.Open();
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr1 = cmd.ExecuteReader();
}
setData(sdr1, currentDetailPanel);
{
query = #"SELECT CareerDay2017, CareerDay2018, CareerDay2019
FROM Institution
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr2 = cmd.ExecuteReader();
}
createYearTable(sdr1, sdr2, currentTaskPanel);
}
}
private void setData(SqlDataReader sdr, Panel DetailPanel1)
{
table.Append("<table>");
table.Append("<tr><th>Institute ID</th> <th>Institute Name</th>");
table.Append("</tr>");
if (sdr.HasRows)
{
while (sdr.Read())
{
table.Append("<tr>");
table.Append("<td>" + sdr[0] + "</td>");
table.Append("<td>" + sdr[1] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table>");
DetailPanel1.Controls.Add(new Literal { Text = table.ToString() });
sdr.Close();
sdr.Dispose();
}
private void createYearTable(SqlDataReader sdr1,SqlDataReader sdr2, Panel DetailPanel2)
{
int currentYear = Int32.Parse(current.ToString("yyyy"));
table.Append("<table>");
//****filling the year
table.Append("<tr>");
for (int i = 1; i <= 12; i++)
{
table.Append("<td>" + Convert.ToString(currentYear) + "</td>");
}
table.Append("</tr>");
//****filling the month
table.Append("<tr>");
for (int j = 1; j <= 12; j++)
{
int monthString = j;
table.Append("<td>" +getMonthName(monthString) + "</td>");
}
table.Append("</tr>");
//****data cell filling
if (sdr2.HasRows)
{
while (sdr2.Read())
{
table.Append("<tr>");
if (yearDropDownList.SelectedValue == "2017")
{
dateColumn = sdr2[5].ToString();
DateTime careerFairDate = Convert.ToDateTime(dateColumn);
int monthNo = Int32.Parse(careerFairDate.ToString("MM"));
int dateNo = Int32.Parse(careerFairDate.ToString("dd"));
for (int j = 1; j <= 12; j++)
{
if (monthNo == j)
{
table.Append("<td>");
Label lbl1 = new Label();
lbl1.Text = "On" + dateNo;
table.Append("</td>");
}
else
{
table.Append("<td>");
Label lbl2 = new Label();
table.Append("</td>");
}
}
}
table.Append("</tr>");
}
table.Append("</table>");
DetailPanel2.Controls.Add(new Literal { Text = table.ToString() });
sdr2.Close();
sdr2.Dispose();
}
}
protected String getMonthName(int i)
{
String[] monthName = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
return monthName[i - 1];
}
protected void searchBtn_Click(object sender, EventArgs e)
{
currentDetailPanel.Visible = false;
currentTaskPanel.Visible = false;
searchDetailPanel.Visible = true;
searchTaskPanel.Visible = true;
con.Open();
if (yearDropDownList.SelectedValue == "2018")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2017")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2017) = '2017'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2019")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2019) = '2019'
ORDER BY InstituteId";
}
cmd = new SqlCommand(query, con);
sdr = cmd.ExecuteReader();
setData(sdr, searchDetailPanel);
DateTime current = DateTime.Now;
createYearTable(sdr,sdr2,searchTaskPanel);
}
As for the UI part, you need to place a breakpoint in the method that draws your UI and step through it while it is reading your data. You need to learn how to debug you code.
Just based off what you have posted, I think you have a bigger issue, you should not be declaring a SqlConnection at the class level, it should be in a method somewhere. For example:
public void GetCalendarData(int year)
{
// You need to use a parameter for the year instead of hard-coding it (note the #year)
string strCmd = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CarrerDay2018) = #year
ORDER BY InstituteId";
using(var conn = new SqlConnection(connString))
using(var cmd = new SqlCommand(strCmd))
{
// add the #year parameter to the command
cmd.Parameters.AddWithValue("#year", year);
conn.Open();
var reader = cmd.ExecuteReader();
// setdata, createYearTable, etc.
conn.Close();
}
}
This way you are not holding a connection to the database for any longer than you need to. Also, I have put the connection and the command inside using statements, meaning that they will be disposed of properly by the garbage collector.
I want to show data from data table on form_load using list box, and later update that data from list box on button click by Insert command. Function for that is fill_List(). This is my code:
OleDbConnection konekcija;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
string putanja = Environment.CurrentDirectory;
string[] putanjaBaze = putanja.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", putanjaBaze[0]);
konekcija = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|\B31Autoplac.accdb");
}
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
fill_List();
}
private void btnUpisi_Click(object sender, EventArgs e)
{
string s1, s2, s3;
s1 = tbSifra.Text;
s2 = tbNaziv.Text;
s3 = tbOpis.Text;
string Upisi = "INSERT INTO GORIVO (GorivoID, Naziv, Opis) VALUES (#GorivoID, #Naziv, #Opis)";
OleDbCommand komUpisi = new OleDbCommand(Upisi, konekcija);
komUpisi.Parameters.AddWithValue("#GorivoID", s1);
komUpisi.Parameters.AddWithValue("#Naziv", s2);
komUpisi.Parameters.AddWithValue("#Opis", s3);
string Provera = "SELECT COUNT (*) FROM GORIVO WHERE GorivoID=#GorivoID";
OleDbCommand komProvera = new OleDbCommand(Provera, konekcija);
komProvera.Parameters.AddWithValue("#GorivoID", s1);
try
{
konekcija.Open();
int br = (int)komProvera.ExecuteScalar();
if(br==0)
{
komUpisi.ExecuteNonQuery();
MessageBox.Show("Podaci su uspesno upisani u tabelu i bazu.", "Obavestenje");
tbSifra.Text = tbNaziv.Text = tbOpis.Text = "";
}
else
{
MessageBox.Show("U bazi postoji podatak sa ID = " + tbSifra.Text + ".", "Obavestenje");
}
}
catch (Exception ex1)
{
MessageBox.Show("Greska prilikom upisa podataka. " + ex1.ToString(), "Obavestenje");
}
finally
{
konekcija.Close();
fill_List();
}
}
Instead of this
It shows me this (added duplicates with new data)
Is there a problem in my function or somewhere else?
Another bug caused by global variables.
You are keeping a global variable for the DataTable filled by the fill_list method. This datatable is never reset to empty when you call fill_list, so at every call you add another set of rows to the datatable and then transfer this data inside the listbox. Use a local variable.
But the same rule should be applied also to the OleDbConnection and OleDbCommand. There is no need to keep global instances of them. Creating an object is really fast and the convenience to avoid global variables is better than the little nuisance to create an instance of the connection or the command.
void fill_List()
{
using(OleDbConnection konekcija = new OleDbConnection(......))
using(OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija))
{
DataTable dt = new DataTable();
konekcija.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(komPrikaz);
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
}
}
Clear your DataTable before filling it again.
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
dt.Clear(); // clear here
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
I have this codes below, but I don't know what is the reason why it was always having errors. Here is the code:
private void btn_acart_Click(object sender, EventArgs e)
{
con.Open();
string[] product = new string[7];
string[] select = new string[2];
int[] num = new int[5];
foreach (ListViewItem item in listView1.SelectedItems)
{
select[1] = item.Text;
string str = "SELECT * FROM [lblProduct] WHERE [prod_id]='"+select[1]+"'";
com = new OleDbCommand(str, con);
read = com.ExecuteReader();
while (read.Read())
{
product[1] = (read["prod_id"].ToString());
product[2] = (read["prod_name"].ToString());
product[3] = (read["prod_price"].ToString());
product[4] = (read["prod_stock"].ToString());
this.listView2.Items.Add(new ListViewItem(new string[] { product[1], product[2], product[3], product[4] }));
cartitems++;
num[1] = int.Parse(product[4]);
num[2] = int.Parse(txt_items.Text);
string strg = "UPDATE lblProduct SET prod_stock='"+(num[1] - num[2]+"' WHERE prod_id='"+product[1]+"'");
com = new OleDbCommand(strg, con);
com.ExecuteNonQuery();
}
}
loaddbase();
con.Close();
txt_items.Text = "0";
}
}
What should I do? What should I change? Please help! The error is always repeating at the read = com.ExecuteReader();
Access Database:
Format: (Field Name - Data Type)
prod_id - AutoNumber
prod_name - Text
prod_price - Text
prod_stock - Text
Are there anything to change in the database?
I have a single TextBox and a search button. The user put multiple comma separated values in a single TextBox (ex. 111,222,333), which are stored in one column (ID), then fetch all the records in the grid view by an MS Access table.
Table name: mytable
Fields:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
444 rajesh 9826789561
555 sudhir 9167849503
Output:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
The following does assertion on text within a text box, see comments. The variable whereCondition will contain the sample SQL statement if all assertion/validation passes.
private void button1_Click(object sender, EventArgs e)
{
string whereStatement = "";
// ensure we have something to work with
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
// Are there commas
if (textBox1.Text.Contains(","))
{
string textValue = textBox1.Text.TrimEnd();
// make sure there is no trailing commas
if (textValue.Last() != ',')
{
string[] parts = textBox1.Text.Split(',');
int badCount = 0;
int testValue = 0;
// see if all values are int
foreach (string item in parts)
{
if (!int.TryParse(item, out testValue))
{
badCount += 1;
}
}
if (badCount == 0)
{
string whereCondition = "ID = " + textValue.Replace(",", " OR ID = ");
whereStatement = string.Format("SELECT [Name], phno WHERE {0} FROM mytable", whereCondition);
}
}
}
else
{
// one id
whereStatement = string.Format("SELECT [Name], phno WHERE ID = {0} FROM mytable", textBox1.Text);
}
}
if (!string.IsNullOrWhiteSpace(whereStatement))
{
MessageBox.Show(whereStatement);
}
else
{
MessageBox.Show("Invald data");
}
}
I HAVE ANOTHER CODE
ITS WORKING
c# CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
//string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\WebSite1\App_Data\MPHS.mdb";
using (OleDbConnection con = new OleDbConnection(constr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
string resultCont = string.Empty;
if (!string.IsNullOrEmpty(txtSearch.Text))
{
string[] contactNames = txtSearch.Text.Trim().Split(',');
foreach (string cont in contactNames)
{
if (!string.IsNullOrEmpty(cont))
{
resultCont = resultCont + ",'" + cont + "'";
}
}
resultCont = resultCont.Remove(0, 1);
cmd.CommandText = "SELECT * FROM myTable WHERE Docnum IN (" + resultCont + ")";
}
else
{
cmd.CommandText = "SELECT * FROM myTable";
}
DataTable dt = new DataTable();
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
Service class
public string[] loadSecretQues(string email)
{
string[] ques= new string[3];
dbConn = new OdbcConnection(dbConnString);
dbConn.Open();
cmd = new OdbcCommand();
cmd.Connection = dbConn;
cmd = new OdbcCommand("SELECT q1, q2, q3 FROM Information WHERE EmailAdd = '" + email + "'", dbConn);
dRead = cmd.ExecuteReader();
while (dRead.Read())
{
if (dRead.HasRows)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
ques[j] = dRead["q" + i].ToString();
}
return ques[i];
}
}
}
}
Page.aspx
protected void btnCheck_Click(object sender, EventArgs e)
{
cmbQues.Items.Add(srvc.loadSecretQues(txtEmail.Text));
}
Good day guys. I am seeking for help. I want to return array values from a function inside a class. The process is, I want to retrieve 3 questions (which are string data type) from my database and store it in a combobox. Any suggestions how to retrieve those three questions? Any other ways? Thanks in advance! :)
You are returning from an inner loop so that rest of iterations ware cancelled, and also you miss to Dispose the command as well as close the open connection. so i suggest you to dispose the command as well as the connection before return, hence the code will be like the following:
no need to check dvc_mst_tdeposit, because if it has no rows control
comes out from while. no need for the outer for Loop(i loop) since
(j Loop is enough to handle this scenario.
dRead = cmd.ExecuteReader();
while (dRead.Read())
{
for (int j = 0; j < 3; j++)
{
ques[j] = dRead["q" + i].ToString();
}
}
dRead.Close();
cmd.Dispose();
dbConn.Close();
return ques;
Use List instead of string array.check the link for advantage
public List<string> loadSecretQues(string email)
{
List<string> ques=new List<string>();
dbConn = new OdbcConnection(dbConnString);
dbConn.Open();
cmd = new OdbcCommand();
cmd.Connection = dbConn;
cmd = new OdbcCommand("SELECT q1, q2, q3 FROM Information WHERE EmailAdd = '" + email + "'", dbConn);
dRead = cmd.ExecuteReader();
if (dRead.HasRows)
{
while (dRead.Read())
{
ques.Add(dRead["yourColumnName"].ToString());
}
}
return ques;
}