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();
}
Related
I am trying to execute this code in getting an error as
There is no row at position 2"
How can I solve this?
public JsonResult Question()
{
try
{
string [] Question=new string[2];
SqlConnection con = new SqlConnection(connectionString: "Server = (localdb)\\mssqllocaldb; Database = QuestionDb; Trusted_Connection = True; MultipleActiveResultSets = true");
con.Open();
string query = "";
query += #"select Id,Sum(Yes) AS T_Yes,Sum(No) AS T_No,Sum(DontKnow) AS T_DontKnow from dbo.Questions Group By Id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
DataTable dt = new DataTable();
SqlDataAdapter cmd1 = new SqlDataAdapter(cmd);
cmd1.Fill(dt);
if (dt.Rows.Count == 0)
{
Question[0] = "0";
Question[1] = "0";
Question[2] = "0";
}
else
{
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[1]["T_No"].ToString();
Question[2] = dt.Rows[2]["T_DontKnow"].ToString();
}
return Json(Question);
The problem is that you are mixing rows and columns. Use:
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[0]["T_No"].ToString();
Question[2] = dt.Rows[0]["T_DontKnow"].ToString();
You must use always dt.Rows[0] (instead of [1] or [2]) to get the properties of the first row.
You're checking only to row count = 0, try this:
Also for comentary answer you need all data for the pie chart so need to recover all records.
Add a reference to System.Data, System.Collections.Generic and System.Linq to your project if this does not compile
List<string[]> listofIdGroups;
List<string[]> listofIdGroups;
listofIdGroups = dt.Rows.OfType<DataRow>()
.Select(dr => new string[3] { dr["T_Yes"].ToString(), dr["T_No"].ToString(), dr["T_DontKnow"].ToString() }).ToList();
you can read the list this way:
foreach (string[] question in listofIdGroups)
{
Console.WriteLine("Yes:" + question[0] + Environment.NewLine + "No: " + question[1] + Environment.NewLine + "DontKnow: " + question[2]);
}
try it here:
https://dotnetfiddle.net/0S1N3c
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"]);
}
I have two buttons(LoadFile and ImportFile). I want to click load file and browser for Excel file from the directy and then click Import button so that it will load the data into the table in the database. Excel Sheet is called "BankStatement" with more than 1000 rows. I haven't done it before, I am doing this using Linq to SQL .
This is my coding but am not sure how to proceed or get the a way. Can someone please help me. Thanks
Loading
public void LoadExcel()
{
string _LoadPath = #"C:\NewFNBFile1.xls";
TextBox1.Text = _LoadPath.ToString();
var _File = new ExcelQueryFactory(_LoadPath);
_File.AddMapping("Number", "Number");
_File.AddMapping("DateReceived", "DateReceived");
_File.AddMapping("Description1", "Description1"
_File.AddMapping("Description2", "Description2");
_File.AddMapping("Description3", "Description3");
_File.AddMapping("Amount", "Amount");
_File.AddMapping("Balance", "Balance");
_File.AddMapping("AccruedCharges", "AccruedCharges");
}
protected void btnBroswer_Click(object sender, EventArgs e)
{
LoadExcel();
}
Import
protected void btnImport_Click(object sender, EventArgs e)
{
var _list = new ExcelQueryFactory(#"C:\NewFNBFile1.xls");
var _Show = from x in _dc.TESTING_NewBankFile1_s
where x ["Description3"] == "A19C28425645285"
select new
{
Number = x["Number"],
DateReceived = x["DateReceived"],
Description1 = x["Description1"],
Description2 = x["Description2"],
Description3 = x["Description3"],
Amount = x["Amount"],
Balance = x["Balance"],
AccruedCharges = x["AccruedCharges"],
};
}
please refer the below c# code
public System.Data.DataTable GetTable(string filename, string SheetName, string outTableName)
{
OleDbConnection oleConn = null;
OleDbDataAdapter oleAdapter = null;
try
{
string Con = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + filename + ";" +
#"Extended Properties=" + Convert.ToChar(34).ToString() +
#"Excel 12.0;" + "Imex=1;" + "HDR=Yes;" + Convert.ToChar(34).ToString() ;
oleConn = new OleDbConnection(Con);
oleConn.Open();
OleDbCommand oleCmdSelect = new OleDbCommand();
oleCmdSelect = new OleDbCommand(
#"SELECT * FROM ["
+ SheetName
+ "$" + "]", oleConn);
oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = oleCmdSelect;
System.Data.DataTable dt = new System.Data.DataTable(outTableName);
oleAdapter.FillSchema(dt, SchemaType.Source);
oleAdapter.Fill(dt);
oleCmdSelect.Dispose();
oleCmdSelect = null;
oleAdapter.Dispose();
oleAdapter = null;
oleConn.Dispose();
oleConn = null;
return dt;
}
}
I need to import .MDB file, read and save in SQL Server.
I tried this:
Method Import
protected void Btn_Importar(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/msaccess")
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Upload/") + filename);
Label1.Text = "File uploaded successfully!";
//ReadMdb();
Insert();
}
}
}
Method Insert
public void Insert()
{
string strFile = Server.MapPath("~/Upload/teste.mdb");
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFile;
var myDataTable = new DataTable();
using (var connection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=" + strFile))
{
connection.Open();
var query = "SELECT * FROM BOLETO";
var command = new OleDbCommand(query, connection);
var reader = command.ExecuteReader();
Conexaocs con = new Conexaocs();
con.Conexao();
SqlCommand sqlComm = new SqlCommand("INSERT INTO BOLETO (CODIGO,NF_CONTA,TEXTO) VALUES (#CODIGO, #NF_CONTA, #TEXTO)", conn);
//if (reader.HasRows)
//{
// while (reader.Read())
// {
// //ListBox1.Items.Add(reader.GetInt32(0).ToString() + " - " + reader.GetString(1));
// }
for (int i = 0; i < reader.FieldCount; i++)
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[i]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[i]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[i]);
sqlComm.ExecuteNonQuery();
}
connection.Close();
}
}
But, when come this point not save!
for (int i = 0; i < reader.FieldCount; i++)
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[i]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[i]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[i]);
sqlComm.ExecuteNonQuery();
}
Message error: System.InvalidOperationException: There are no data for the row or column
Some idea? Thanks
As Gord Thompson say you need to iterate through the rows, not the fields. Try the following (untested) code:
if (reader.HasRows)
{
while (reader.Read())
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[0]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[1]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[2]);
sqlComm.ExecuteNonQuery();
}
}
Não existem dados para a linha ou coluna
apparently means
There are no data for the row or column
You opened the OleDbDataReader but you didn't Read() from it. (You did once upon a time, but that while loop has been commented out.)
I have 2 ListBoxes and five textBox. In ListBox_prod i want to retrieve all product (from PRODUCT table) and in Listbox_item i want to retrieve all Items corresponding to the selected Product (from PRODITEM table) on form load event. All the products have more than 1 items associated with them. Problem is with the Listbox_item as it is showing only 1 item. But I want all items to be displayed in Listbox_item when a particulat product is selected. getData() in class DBCommands actually causes the problem. Here's my code:
public partial class form_prodItems : Form
{
private DBCommands dBCommand;
public form_prodItems()
{
InitializeComponent();
listBx_prod.SelectedIndexChanged += new EventHandler(listBx_prod_selValChange);
listBx_item.SelectedIndexChanged += new EventHandler(listBx_item_selValChange);
}
private void form_prodItems_Load(object sender, EventArgs e)
{
// ...
refresh_listBx_prod("PRODUCT", this.listBx_prod, null, null);
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void listBx_item_selValChange(object sender, EventArgs e) // causing problem
{
if (listBx_item.SelectedValue != null)
showPrice("PRODITEM", listBx_item.ValueMember, listBx_item.SelectedValue.ToString());
}
private void listBx_prod_selValChange(object sender, EventArgs e)
{
if(listBx_prod.SelectedValue != null)
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void showPrice(string tblName,string where_column ,string where_val)
{
DataSet ds;
ds = dBCommand.getData("select * from " + tblName + " WHERE " + where_column + " = '" + where_val + "'");
DataRow col_val = ds.Tables[0].Rows[0];
txtBox_12oz.Text = col_val.ItemArray[3].ToString();
txtBox_16oz.Text = col_val.ItemArray[4].ToString();
txtBox_20oz.Text = col_val.ItemArray[5].ToString();
txtBox_1lbs.Text = col_val.ItemArray[6].ToString();
txtBox_2lbs.Text = col_val.ItemArray[7].ToString();
//ds.Clear();
}
private void refresh_listBx_prod(string tblName, ListBox listBox, string where_column, string where_val)
{
DataSet ds = new DataSet();
dBCommand = new DBCommands();
if (where_column == null)
{
ds = dBCommand.getData("SELECT * FROM " + tblName);
}
else
{
ds = dBCommand.getData("SELECT * FROM " + tblName + " WHERE " + where_column + " = " + where_val);
}
listBox.DataSource = ds.Tables[0];
// ds.Clear();
}
}
public class DBCommands
{
private SqlConnection conn;
private SqlDataAdapter dataAdapter;
private DataSet container;
public DataSet getData(string selectCmd)
{
container.Clear(); // I guess something needs to be fixed here some where..
conn = getConnection();
dataAdapter.SelectCommand = new SqlCommand(selectCmd, conn);
dataAdapter.Fill(container);
conn.Close();
return container;
}
private SqlConnection getConnection()
{
SqlConnection retConn = new SqlConnection("Data Source=" + Environment.MachineName + "; Initial Catalog=RESTAURANT; Integrated Security = TRUE");
retConn.Open();
return retConn;
}
}
Actually dataset flushes all data it had got from (SELECT * FROM PRODITEM where PRODUCT_id = '1') and shows data from the last executed query i-e (select * from proditem where item_id = 1)
Any suggestions..
my suggestion is trying to run the command via SqlCommand.
that way you will have better knowledge on what you get back.
use this example:
SqlCommand command = new SqlCommand(selectCmd, conn);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
and modify it so you'll return a table as you need.
the reason i offer you this is that it's easy to use and you get immediate debug information that help you understand sql mistakes