C# loading data from MS Access database to listbox - c#

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.

Related

how to delete data from data grid view using ms access in c#

private void Delete_Click(object sender, EventArgs e)
{
//i have used this query for delete button
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter();
OleDbConnection con = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb");
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb";
con.Open();
//this is the query i have used
OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
con.Close();
}
//i have table named:car_model & attribute as Description
Your quotes don't look right, but my eyes are not great and anyway, the compiler would pick that up immediately, so I guess it's something else.
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = #Des", con);
comm.Parameters.AddWithValue("#Des", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
Also, use the '#' character to prevent SQL Injection issues. I don't think this is necessarily a problem with MS Access, but it's a good habit to get into.
https://www.w3schools.com/sql/sql_injection.asp

oledb connection string not initialized

namespace PCMS
{
public partial class frmPlayerInterface : Form
{
private OleDbConnection con = new OleDbConnection();
OleDbCommand com = new OleDbCommand();
private DataTable dt = new DataTable();
public frmPlayerInterface(string getUser)
{
InitializeComponent();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\SDP\PCMS\SDP.accdb";
lblUser.Text = getUser;
}
private void btnEnquire_Click(object sender, EventArgs e)
{
frmEnquire frmenq = new frmEnquire();
frmenq.ShowDialog();
}
private void btnTopUp1_Click(object sender, EventArgs e)
{
frmTopUp frmTU = new frmTopUp();
frmTU.ShowDialog();
}
private void frmPlayerInterface_Load(object sender, EventArgs e)
{
con.Open();
OleDbCommand comm = new OleDbCommand();
String sql = "select Balance from PlayerAccount where Player_User=#user";
comm.Parameters.Add(new OleDbParameter("user", lblUser.Text));
comm.CommandText = sql;
OleDbDataReader cursor = comm.ExecuteReader();
while (cursor.Read())
{
lblBalance.Text = cursor["Balance"].ToString();
}
con.Close();
}
}
}
Hey sorry guys asking this again but ive been trying this for the past three hours and wave the white flag. Still getting the same error.
I just want to have the selected balance value from the database to be shown in the label.
Thanks ><
You're not associating the connection with the command object:
con.Open();
String sql = "select Balance from PlayerAccount where Player_User=#user";
OleDbCommand comm = new OleDbCommand(sql, con);
Note that reusing a connection is not always the best design. Connections are pooled in .NET, so recreating them is generally not an expensive operation. A better design would be to store the connection string as a class property then just create a connection when you need it:
private string ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\SDP\PCMS\SDP.accdb";
// or better yet - pull form app.config...
and when you use it:
String sql = "select Balance from PlayerAccount where Player_User=#user";
using(OleDbConnection con = new OleDbConnection(ConnectionString))
{
con.Open();
using(OleDbCommand comm = new OleDbCommand(sql, con))
{
... Add parameters, execute query, return results
}
}

Cannot reuse open DataReader

I am writing a c# windows forms application and i am coming accross the error mentioned above. I think this is happening because i am opening an sql connection and reader object in my main form load object and then doing the same thing again in another click event handler. I am not sure what i need to do in order to change my code / stop this from happening (or if this is even the problem). I have tried turning MARS on in my connection string but this did not fix the problem. Below is my code.
namespace Excel_Importer
{
public partial class Export : Form
{
public Export()
{
InitializeComponent();
}
private void cmbItemLookup_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Export_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings ["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From ExportItem", conn);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ExportItemName", typeof(string));
dt.Load(rdr);
cmbItemLookup.DisplayMember = "ExportItemName";
cmbItemLookup.DataSource = dt;
conn.Close();
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn);
SqlDataReader rdr2;
rdr2 = cmd2.ExecuteReader();
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
You need to close your DataReaders. They implement the IDisposable interface, so the simplest thing is to put them inside a using block:
using (rdr = cmd.ExecuteReader())
{
..
} // .NET always calls Dispose() for you here
Actually, you pretty much have to dispose of everything that implements IDisposable, or problems gonna happen.
As the other answer points out, you must tidy up your clicked event code:
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString) )
{
conn.Open();
using(SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn) )
{
using(SqlDataReader rdr2= cmd2.ExecuteReader())
{
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
}

confused about how populate listview

I have a table with 2 columns: username and age. What I want to do is to populate a ListView with data coming from the database. I think I missed out something because every time the form is loaded the ListView is empty. I have noticed that the DataReader's property HasRows return false while debugging.
void populate()
{
SqlCommand cmd = new SqlCommand("select * from users ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListViewItem lvi = new ListViewItem(dr[0].ToString());
lvi.SubItems.Add(dr[1].ToString());
listView1.Items.Add(lvi);
}
dr.Close();
dr.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
using (con = new SqlConnection("server=.\\sqlepxress;database=Projects;Integrated Security=sspi")) {
try
{
con.Open();
populate();
}
catch (SqlException x )
{
MessageBox.Show(x.Message);
}
}
}
your Connection string isn't valid, try:
con = new SqlConnection("Data Source=....;Initial Catalog=..;Connect Timeout=15;Integrated Security=sspi";
OR (in case Windows Authendication has problems :)
new SqlConnection("Data Source="+...+";Initial Catalog=Projects;User id="+user+";Password="+pass+";Connect Timeout=15;Integrated Security=false");

Autocomplete for domain users

Is there any way to do autocomplete for domain users in .net?
Meaning, I want a textbox that when I will start and type Admin, it will complete it to \Administrator
Thanks.
Sure, you can hold a list of all valid domain account names and use an autocomplete (winforms example) with that data source.
Of course, this means you are exposing some sensitive information.
you can try like this for displaying domain user names ......
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection = ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" + " order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show(" this is autocomplete text box example");
}
}
}

Categories

Resources