c# display Access Database in DataGridView - c#

First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.

your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;

Related

Refresh DataGridView after inserting values

I have established connection and inserted values into the table.
However, I am not sure the best method to refresh the DataGridview as the values have been inserted after click button.
private void button1_Click(object sender, EventArgs e)
{
{
string theText = makeTextBox.Text;
string theText2 = modelTextBox.Text;
var value = Convert.ToInt32(yearTextBox.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
dataGridView1.DataSource = carsBindingSource;
dataGridView1.Refresh();
cnn.Close();
}
}
}
}
enter image description here
EDIT:
here is the code with the working solution of rebinding the datasource and then it will update:
{
string theText = textBox1.Text;
string theText2 = textBox2.Text;
var value = Convert.ToInt32(textBox3.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
cnn.Close();
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = carsTableAdapter.GetData();
dataGridView2.DataSource = carsBindingSource;
}
}```
Your code is missing the part where the carsBindingSource variable is initialized with data. From your limited code, it should be noted that… if you add/insert a new row into the table in the data base, then this is NOT going to automatically update the carsBindingSource.
It is unknown “what” is used as a DataSource to the carsBindingSource. OR, how this data source is populated. I will assume the DataSource to the BindingSource is a DataTable and that somewhere in the code it is getting this DataTable from a query to the data base. If this process is not already in a single method that returns a DataTable, then, I recommend you create one, and it may look something like…
private DataTable GetCarsDT() {
DataSet ds = new DataSet();
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "SELECT * FROM Cars";
using (SqlDataAdapter da = new SqlDataAdapter(command)) {
da.Fill(ds, "Cars");
return ds.Tables[0];
}
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
return null;
}
Above will return a DataTable with three (3) columns, Make, Model and Year. This DataTable is used as a DataSource to the BindingSource… carsBindingBource.
Now in the button1_Click event, the code inserts the new values into the data base. However, the carsBindingSource will still contain the data “before” the new items were added to the DB. Therefore, we can simply use the method above to “update” the carsBindingSource after the new items are added to the DB.
Note: you can go two routs here, 1) as described above, simply update “all” the data in the binding source… OR … 2) after updating the new items into the data base, you can also add the new items to the binding source’s data source… i.e. its DataTable. Either way will work and unless there is a large amount of data, I do not think one way would be preferred over the other.
Below shows what is described above. Note, the commented code adds the new items directly to the DataTable. You can use either one but obviously not both.
private void button1_Click(object sender, EventArgs e) {
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
command.Parameters.Add("#Make", SqlDbType.NChar, 50).Value = makeTextBox.Text.Trim();
command.Parameters.Add("#Model", SqlDbType.NChar, 50).Value = modelTextBox.Text.Trim();
int.TryParse(yearTextBox.Text.Trim(), out int year);
command.Parameters.Add("#Year", SqlDbType.Int).Value = year;
command.ExecuteNonQuery();
carsBindingSource.DataSource = GetCarsDT();
//DataTable dt = (DataTable)carsBindingSource.DataSource;
//dt.Rows.Add(makeTextBox.Text.Trim(), modelTextBox.Text.Trim(), year);
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
}
Putting all this together…
BindingSource carsBindingSource;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = GetCarsDT();
dataGridView1.DataSource = carsBindingSource;
}
Hope this makes sense.
I dont think its possible. You may need to create a separate button to submit and then refresh the data

Query single data from SQLite to C# textbox or label

I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);

sql search query in c#

I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}

Errors when retrieving values from database determined by combobox to gridview

I have a code to get all the values from database determined by a combobox to a datagridview.
But whenever i run it , i get invalid column name for ListU.SelectedValue , and the multi-part identifier "System.Data.DataRowView" could not be bound if i am using ListU.SelectedItem.
where did i go wrong? i am guessing it is either my code or it is my table.
private void User_Load(object sender, EventArgs e)
{
SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
DataTable dt1 = new DataTable();
ListU.DataSource = dt1;
daSearch.Fill(dt1);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}
and the button code -
private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName =" + ListU.SelectedValue, conn);
DataTable dts3 = new DataTable();
daS.Fill(dts3);
dataGridView1.DataSource = dts3.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
conn.Close();
}
you should use SqlParameter ... helps against sql injection problems and also against missing quotes ... like this:
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = #name", conn);
daS.SelectCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = ListU.SelectedValue;
this assumes that cName is a string ... if not you'll have to change the SqlDbType ...

How do i bind data source to a ComboBox?

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference
Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer

Categories

Resources