This is an ordering system, it is our project for the finals. I want to show the rows inside the "Order" table, but it doesn't display the rows inside the table. It displayed on the "Items" table, maybe because it was the first table I made?
if (choice == 1)
{
OpenCon();
Console.WriteLine("ITEM NUMBER ITEM STOCK");
Console.WriteLine("------------------------------------------");
DataTable dt = LoadData("SELECT * FROM Items");
for (int r = 0; r < dt.Rows.Count; r++)
{
Console.Write(dt.Rows[r]["ItemNumber"].ToString() + " ");
Console.Write(dt.Rows[r]["Item"].ToString() + " ");
Console.Write(dt.Rows[r]["Stock"].ToString());
Console.WriteLine();
}
CloseCon();
}
else if (choice == 2)
{
OpenCon();
Console.WriteLine("ITEM NUMBER ITEM QUANTITY");
Console.WriteLine("------------------------------------------");
DataTable dt2 = LoadData("SELECT * FROM Order");
for (int i = 0; i <dt2.Rows.Count; i++)
{
Console.WriteLine(dt2.Rows[i]["ItemNumber"].ToString());
Console.WriteLine(dt2.Rows[i]["OrderedItem"].ToString());
Console.WriteLine(dt2.Rows[i]["Quantity"].ToString());
}
CloseCon();
}
I created a method to open and close the connection and to load the data from MS Access.
public static void OpenCon()
{
con = new OleDbConnection();
string path = #"C:\Users\Acer\Documents\OSystem.accdb";
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + path;
con.Open();
}
public static void CloseCon()
{
con.Dispose();
con.Close();
}
private static DataTable LoadData(string query)
{
adptr = new OleDbDataAdapter(query, con);
cmd = new OleDbCommandBuilder(adptr);
dTable = new DataTable();
adptr.Fill(dTable);
return dTable;
}
Related
I'd like to get any of my tables record in arraylist and get it in another form (no matter how much columns for loop will retrieve data in to arraylist)
Here my code:
public static ArrayList getrecord(String Table, String Column, Int32 id)
{
ArrayList asd = new ArrayList();
Form1.con.Close();
Form1.con.Open();
SqlCommand sq = new SqlCommand("Select * from " + Table + " where " + Column + " = " + id, Form1.con);
SqlDataReader sdr = sq.ExecuteReader();
if (sdr != null)
{
while (sdr.Read())
{
for(int i =0; i < sdr.FieldCount; i++)
{
asd.Add(sdr.GetValue(i).ToString());
}
}
}
return asd;
}
I suggest using DataTable instead of ArrayList. You can fill DataTable with all the records you need and use it in another form.
System.Data.SqlClient.SqlCommand sq = new System.Data.SqlClient.SqlCommand("your sql query", "your connection string");
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(sq);
sda.Fill(dt);
I have a code that importing and displaying a excel file to datagridview and I'm wondering if you help me to how can I save those sheet from my excel file to my database in mysql?? My sheet name are 1st grading, 2nd grading and attendance, I'm using c#. Anyway here's my code:
private void btnSaved_Click(object sender, EventArgs e)
{
int qtr = 0;
string att_qtr = "ATTENDANCE";
MySqlConnection con = new MySqlConnection("Server = DESKTOP-9H7QBOH; Database = sti_spms; UID = root; Password = 1234;");
try
{
string query = "INSERT INTO tbl_secondsem_grades(STUDENT_NO, NAME, SUBJECT, SECTION, GRADE, INITIAL_GRADE, QTR)" + "Values(#STUDENT_NO, #NAME, #SUBJECT, #SECTION, #GRADE, #INITIAL_GRADE, #QTR)";
query += "INSERT INTO tbl_attendance(STUDENT_ID, NAME, SUBJECT, SECTION, TOTAL_ABSENCES)" + "Values(#STUDENT_ID, #NAME, #SUBJECT, #SECTION, #TOTAL_ABSENCES)";
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
if(quarter.Equals("1st QTR"))
{
qtr = 1;
}
else if(quarter.Equals("2nd QTR"))
{
qtr = 2;
}
else if(quarter.Equals("3rd QTR"))
{
qtr = 3;
}
else if(quarter.Equals("4th QTR"))
{
qtr = 4;
}
else if (quarter.Equals("ATTENDANCE"))
{
att_qtr = "ATTENDANCE";
}
else
{
MessageBox.Show("Error!");
}
//int num = Convert.ToInt32(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#INITIAL_GRADE", dataGridView1.Rows[i].Cells["INITIAL GRADE"].Value.ToString());
cmd.Parameters.AddWithValue("#GRADE", dataGridView1.Rows[i].Cells["QG"].Value.ToString());
cmd.Parameters.AddWithValue("#QTR", qtr);
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#Total_Absences", dataGridView1.Rows[i].Cells["Total_Absences"].Value.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Data Sucessfully Saved!");
}
}
Quickie partial
...
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
cmd.Paramters.Add("#STUDENT_NO", MySqlDbType.Int); .. guessing this is an int - otherwise choose type
cmd.Paramters.Add("#NAME", MySqlDbType.String);
... // add rest here
con.Open();
...
for (.. ) {
...
int studentno;
int.TryParse(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString(), out studentno);
cmd.Paramters["#STUDENT_NO"].Value = studentno;
cmd.Paramters["#NAME"].Value = dataGridView1.Rows[i].Cells["NAME"].Value.ToString();
...
}
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'm new to MVC and I am trying to build a DataTable from a stored procedure response and pass it back to my View. For the rows I build a comma delimited string full of cell values.
The issue I am having is that the string is not getting parsed by the commas, and effectively it is passing the whole string into the first cell of each row.
What is the correct way to build up a row comprised of the individual values for each column? The number of columns, their names, and amount of records returned are all variable.
public ActionResult dataSet(string table, string key, string search)
{
SqlDataReader rdr = null;
SqlConnection con = new SqlConnection("Connection stuff");
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("dbo.USP_getDataSet", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#key", key);
cmd.Parameters.AddWithValue("#table", table);
cmd.Parameters.AddWithValue("#search", search);
con.Open();
DataTable theTable = new DataTable();
try
{
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int count = rdr.FieldCount;
string rowString = "";
int intRows = theTable.Columns.Count;
//Build columns on first pass through
if (intRows == 0){
for (int i = 0; i < count; i++){
theTable.Columns.Add(Convert.ToString(rdr.GetName(i).TrimEnd()), typeof(string));
}
}
//Grab all values for each column
for (int i = 0; i < count; i++){
rowString += '\"' + (Convert.ToString(rdr.GetValue(i)).TrimEnd()) + '\"' + ", ";
}
//Remove trailing delimiter
string finishedRow = rowString.Substring(0, rowString.Length - 2);
//Add the full row for each time through reader
theTable.Rows.Add(finishedRow);
}
}
finally
{
if (rdr != null)
{ rdr.Close(); }
if (con != null)
{ con.Close(); }
}
return View(theTable);
}
According to the documentation for the DataRowCollection.Add(params Object[] values) method, each value passed in will populate each cell. Since you are passing in a single value, it is the value of the cell.
You probably want:
var cells = new object[count];
for (int i = 0; i < count; i++)
{
cells[i] = rdr.GetString(i).Trim() + "\"
}
theTable.Rows.Add(cells)
I have 2 DataTable
string query = "Select * from " + ServerTableName;
DataTable oDtSeverData = GetDataTable(query);
string dbQuery = "SELECT * from " + LocalSystemTableName;
DataTable oDtLocalSystemData = dataService.GetDataTable(dbQuery);
I want to compare(Row and Column) both the datatable, to get same column(exist in both the datatable) with Unique records(unique Row).
Let me explain in details:
oDtServerData have columns (Column1, Column2, Column3, Column4) with few rows.
oDtLocalSystemData have columns (Column1, Column2, Column3) with few rows.
it is possible that oDtServerData can have less columns and oDtLocalSystemData. but in any case I want the column (Column1, Column2, Column3) which is matching in both the datatable with unique rows(data should be unique).
Someone please help me in this and give me some idea with few examples to solve my problems.
you can use the below code to compare two DataTable,
public static DataTable CompareTwoDataTable(DataTable dt1, DataTable dt2)
{
dt1.Merge(dt2);
DataTable d3 = dt2.GetChanges();
return d3;
}
For more information about DataTable.Merge(), please refer to DataTable.Merge Method (DataTable) on MSDN.
ArrayList commonColumns = new ArrayList();
for (int iServerColumnCount = 0; iServerColumnCount < oDtSeverData .Columns.Count; iServerColumnCount ++)
{
for (int iLocalColumnCount = 0;
iLocalColumnCount < oDtLocalSystemData .Columns.Count;
iLocalColumnCount ++)
{
if (oDtSeverData .Columns[iServerColumnCount ].ColumnName.ToString()
.Equals(oDtLocalSystemData .Columns[iLocalColumnCount].ColumnName.ToString()))
{
commonColumns.Add(oDtLocalSystemData .Columns[iLocalColumnCount].ColumnName.ToString());
}
}
}
DataTable oDtData = CompareTwoDataTable(oDtLocalSystemData, oDtSeverData,commonColumns);
public DataTable CompareTwoDataTable(DataTable dtOriginalTable, DataTable dtNewTable, ArrayList columnNames)
{
DataTable filterTable = new DataTable();
try
{
filterTable = dtNewTable.Copy();
string filterCriterial;
if (columnNames.Count > 0)
{
for (int iNewTableRowCount = 0; iNewTableRowCount < dtNewTable.Rows.Count; iNewTableRowCount++)
{
filterCriterial = string.Empty;
foreach (string colName in columnNames.ToArray())
{
filterCriterial += "ISNULL("+colName.ToString() + ",'')='" + dtNewTable.Rows[iNewTableRowCount][colName].ToString() + "' AND ";
}
filterCriterial = filterCriterial.TrimEnd((" AND ").ToCharArray());
DataRow[] dr = dtOriginalTable.Select(filterCriterial);
if (dr.Length > 0)
{
filterTable.Rows[filterTable.Rows.IndexOf(filterTable.Select(filterCriterial)[0])].Delete();
filterTable.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
}
return filterTable;
}
I was trying to insert data to table to I used bulk insert for that i used same common column
public bool BulkInsertDataTable(string tableName, DataTable dataTable, string[] commonColumns)
{
bool isSuccuss;
try
{
SqlConnection SqlConnectionObj = GetSQLConnection();
SqlBulkCopy bulkCopy = new SqlBulkCopy(SqlConnectionObj, SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.UseInternalTransaction, null);
bulkCopy.DestinationTableName = tableName;
bulkCopy.ColumnMappings.Clear();
for (int iDtColumnCount = 0; iDtColumnCount < dataTable.Columns.Count; iDtColumnCount++)
{
for (int iArrCount = 0; iArrCount < commonColumns.Length; iArrCount++)
{
if (dataTable.Columns[iDtColumnCount].ColumnName.ToString().Equals(commonColumns[iArrCount].ToString()))
{
bulkCopy.ColumnMappings.Add(dataTable.Columns[iDtColumnCount].ColumnName.ToString(),
commonColumns[iArrCount].ToString());
}
}
}
bulkCopy.WriteToServer(dataTable);
isSuccuss = true;
}
catch (Exception ex)
{
isSuccuss = false;
}
return isSuccuss;
}