Database Access in Combobox - c#

How to insert the database access column in combobox, on button click?it has 1 column

Try this:
create a private method that get msaccess data and bind to a datatable:
private DataTable BindData()
{
using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\YOURDB.mdb; PersSecurity Info=False;")) /your connectionsting
{
using (var dAd = new OleDbDataAdapter("select ID,column1 from Table ", conn)) //select query from your DB
{
var dSet = new DataTable();
try
{
conn.Open();
dAd.Fill(dSet);
return dSet;
}
catch
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
}
Then on your button click Add
var dt = BindData();
cmbBox.DataSource = dt;
cmbBox.DisplayMember = "column1"; //Display Table Column on your DB
cmbBox.ValueMember = "ID";
See also:
The C# Station ADO.NET Tutorial
Regards

Related

show data in Listbox c# from sql

I have this code to show data from SQL to listbox in c#
public DataTable get_mada_listbox()
{
DAL.DATAACSESSLAYER dal = new DAL.DATAACSESSLAYER();
dal.open();
DataTable dt = new DataTable();
dt = dal.selectData("get_mada_listbox", null);
dal.close();
return dt;
}
When I call the function:
BL.cls_product prd = new BL.cls_product();
listBox1.DataSource = prd.get_mada_listbox();
The listbox should show
system.data.data row view.
How can I solve it?
i solve my problem by add
listBox1.DisplayMember = "mada_name";
next this
listBox1.DataSource = prd.get_mada_listbox();
thx
This should be your method:
void get_mada_listbox()
{
var connection = ConfigurationManager.ConnectionStrings[name].ConnectionString;
using (SqlConnection connsql = new SqlConnection(connString))
{
connsql.Open();
// Sql Adapter
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM DataTable", connection))
{
// fill a data table
var data_table = new DataTable();
sqlAdapter.Fill(t);
// Bind the table to the list box
listBox1.DisplayMember = "mada_name";
listBox1.ValueMember = "mada_value";
listBox1.DataSource = data_table;
}
}
}

Datagridview not updating/refreshing

I have a DataGridView made of a DataSet of a table from the DB. When I delete a row, it is updated in the database but it is not removed from the GridView. Only when I restart the application does it get removed from the GridView.
Please help
You need to reset the binding on your bindingsource.
bindingSource.ResetBindings(false);
This is a very simple process.
1.) Create a Binding Source
2.) Set the Datasource for this object to your Dataset Table.
3.) Set The datasource for your DatagridView as the Binding source Object.
Code Example:
Dataset ds = new Dataset();
BindingSource bs = new BindingSource()
bs.Datasource = ds.Table[0];
DatagridView.Datasource = bs;
Now, Any changes you make in the DataTable will ripple through to your GridView automatically.
Hope this helps you?
if you are showing your table in dgv and for deleting something from that table you have a button on your win form. you chose let's say ID and click "delete" button for delting an item from db table. Here is that code:
private void btn_Delete_Click(object sender, EventArgs e)
{
int selectedCellCount = dgv.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
string selection;
for (int i = 0; i < selectedCellCount; i++)
{
selection = dgv.SelectedCells[i].Value.ToString();
string qs_delete = "DELETE FROM yor_table WHERE id = '" + selection + "';";
try
{
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = qs_delete;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
//don't forget to load your table again in dgv
string qs_select = "SELECT * FROM your_table";
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Clear();
dgv.DataSource = dataTable;
try
{
conn = new MySqlConnection(cs);
cmd = new MySqlCommand(qs_select, conn);
conn.Open();
da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
cb = new MySqlCommandBuilder(da);
dgv.DataSource = dataTable;
dgv.DataMember = dataTable.TableName;
dgv.AutoResizeColumns();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
You'll notice here that i have MySQL db but don't bother yourself with that.
If database is updated and you want to refresh DataGridView, call this:
this.<table name>TableAdapter.Fill(this.<DB name>DataSet.<table name>);
For example: Where is name of your table (for example Customers) and is name of your database (for example MyDB).
this.CustomersTableAdapter.Fill(this.MyDBDataSet.Customers);
You have to call this function after every deletion(Re-bind Grid).
void BindGrid()
{
YourDataGridView.DataSource = dataset;
YourDataGridView.DataBind();
}

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}

Populate Combobox with Access Table Names

I have a datatable that I am able to populate from my access database without a problem but I want to add a step in it:
private void button_Open_Click(object sender, EventArgs e)
{
var open = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = #"Access Files (*.mdb)|*.mdb|All files (*.*)|*.*",
FilterIndex = 0,
RestoreDirectory = true,
Multiselect = false
};
open.ShowDialog();
if (string.IsNullOrEmpty(open.FileName)) return;
try
{
var con = new OleDbConnection();
con.ConnectionString = "Provider= microsoft.jet.oledb.4.0; data source = " + open.FileName;
con.Open();
var dt = new DataTable();
var da = new OleDbDataAdapter("select * from tblCustomerAccount", con);
da.Fill(dt);
dataGridView_AccessDatabase.DataSource = dt.DefaultView;
con.Close();
}
catch (OleDbException ex)
{
//get the error message if connection failed
MessageBox.Show("Error in connection ..." + ex.Message);
}
}
I'd like to add in there a combobox that is populated with the table names then, off the selection of the combobox, the datatable is populated.
How do I populate the combobox with the table names?
Thanks!
//
string[] restrictions = new string[4];
restrictions[3] = "Table";
con.Open();
DataTable tabls=con.GetSchema("Tables",restrictions);
return a datatable that a column of that represent table names
you can bind this datatable to combobox and set datamemebr to TABLE_NAME

Unable to populate lsitbox in asp.net web application

I am trying to populate a list box from a customers table in SQL database.I tested with WPF list box the code is working good but when i try to implement in asp.net web application i am unable to populate the list box. Here is my code
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query , conn);
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
listbox1.SelectedValue = row["customer_ID"].ToString();
samplelist.Add(listbox1.SelectedValue);
}
listbox1.DataSource = samplelist;
}
catch (Exception)
{
}
Can any one guide me in the right direction ?
Try using the below code:
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(ds);
listbox1.DataSource = ds.Tables[0];
listbox1.DataTextField = "WORKSTATION_ID";
listbox1.DataValueField = "WORKSTATION_ID";
listbox1.DataBind();
}
catch (Exception)
{
}
foreach (DataRow row in ds.Tables[0].Rows)
{
samplelist.Add(row["WORKSTATION_ID"].ToString());
}
listbox1.DataSource = samplelist;
listbox1.DataBind();
You should be able to trim this down somewhat to the following. You're missing the DataBind() as well.:
try
{
//Existing to fill ds, check table exists, etc.
listbox1.DataSource = ds.Tables[0];
listbox1.DataValueField = "COLUMNNAME";
listbox1.DataTextField = "COLUMNNAME";
listbox1.DataBind();
}
catch (Exception)
{
}

Categories