Populate Combobox with Access Table Names - c#

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

Related

C# Add Combobox and Checkbox for DataGridView Combined SQL Table

I have a table as following in SQL Database. Devicereg Table.
No | Parameter | DataTyp | Enable |
1 xxxx Int True
2 yyyy Int True
3 tttt String False
I want to show these data in DataGridView and its DataTyp column want to add Combobox with default value table cell value, Enable column want to add a checkbox with default value table cell value.
Combobox want to add the following list and the default value is one of following value.
Int
String
Floart
Following code, Combobox value adds all columns value in one combo box.
Code:
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
bool st = false;
DataSet ds = new DataSet();
connection = new SqlConnection(connetionString);
sql = "select * from Devicereg";
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand(sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = null;
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.Tables[0];
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.ValueMember = "Datatyp";
dataGridView1.Columns.Add(dc);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Example Photo:
Edit 1:
I have done it but how to display only defined items in the dropdown.
Code:
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
I have 36 rows and all rows Datatyp values shows. I want specific items to select like Int, Flort, Strings only.
Output:
Edit 2:
If I set like the following code, I got error message.
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = new List<string> { "Int", "String", "Flort" };
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
Error:
To import the DataTyp from database to DataGridViewComboBoxColumn, please refer to the following steps.
First, add the columns to datagridview.
Set the DataTyp's columntype to DataGridViewComboBoxColumn, and set its DataSource like:
Next, set Enable columntype to DataGridViewCheckBoxColumn.
Or via code:
var colNo = new DataGridViewTextBoxColumn
{
HeaderText = "No",
Name = "No"
};
var colParameter = new DataGridViewTextBoxColumn
{
HeaderText = "Parameter",
Name = "Parameter"
};
var colDataTyp = new DataGridViewComboBoxColumn
{
HeaderText = "DataTyp",
Name = "DataTyp",
DataSource = new List<string> { "Int", "String", "Float" }
};
var colEnable = new DataGridViewCheckBoxColumn
{
HeaderText = "Enable",
Name = "Enable"
};
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { colNo, colParameter, colDataTyp, colEnable });
Then fill the datagridview via the code below.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From Devicereg", conn);
ds = new DataSet();
sda.Fill(ds, "T1");
}
DataGridViewComboBoxCell typeCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["No"].Value = row[0];
dataGridView1.Rows[index].Cells["Parameter"].Value = row[1];
typeCell = (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["DataTyp"]);
typeCell.Value = row[2].ToString().Trim();
dataGridView1.Rows[index].Cells["Enable"].Value = row[3];
}
The result,

data is not getting deleted from database

In windows desktop application form I am using this code for deleting data from datagridview and database ,I have taken one checkbox column in dataridview ,If I click on checkbox row is getting deleted at that moment from datagridview ,but not from the database therefore when i reload form i can see that row again ,where I am going wrong?
public partial class EditEngClgList : Form
{
private OleDbConnection acccon = null;
private OleDbDataAdapter da = null;
private DataTable dt = null;
private BindingSource bs = null;
private OleDbCommandBuilder cmdb = null;
public EditEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
MessageBox.Show("Error:" + err);
}
string sql = "Select * From EngColeges order by EngClgID";
da = new OleDbDataAdapter(sql, acccon);
cmdb = new OleDbCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dataGridView1.Columns[1].Visible = false;
dataGridView1.Columns[2].HeaderText = "Engineering College Name";
dataGridView1.Columns[3].HeaderText = "Adress";
dataGridView1.Columns[4].HeaderText = "Entrance Type";
dataGridView1.Columns[2].Width = 400;
}
private void button4_Click(object sender, EventArgs e)
{
List<int> checkedclg = new List<int>();
DataRow dr;
List<int> checkedclgid = new List<int>();
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
}
foreach (int k in checkedclg)
{
dr = dt.Rows[k];
dt.Rows[k].Delete();
foreach (int j in checkedclgid)
{
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
oleDbCommand.Parameters.Add("#clgID", OleDbType.Integer).Value = j;
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
}
}
}
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
Looks like the wrong cell value is being passed to Convert.ToInt16? It's using the "Deleted" column instead of your ID column.
Also you can delete all the rows in one sql statement using the where in clause, for example:
DELETE FROM table WHERE id IN (1, 2, 3, 4)
Insted of storing value of Delete like this
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
storing The values of primary key column like this deletes data properly from database Also
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["EngClgID"].Value));
You must change this line:
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
to the following:
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["CellInTheInvisible‌​Column"].Value));
Because you're converted a boolean type to Int16 and then you're used it in your query for checking with ID in your related table.
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
So, you must store ID of rows that you want to delete them.
I think first of all you are deleting the row and then you are attempting to delete it from database. First of all you delete the row from database and then again call the select query for that table.
All you have right now is a command. You need your OleDbDataAdapter, and pass the command to it:
...
da = new OleDbDataAdapter(sql, acccon);
da.DeleteCommand = oleDbCommand;
More Info: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx
Just replace these two lines:
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
With:
da.DeleteCommand = oleDbCommand;
References:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx

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();
}

Database Access in Combobox

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

how to refresh a data grid?

i m using c# as front end and ms access as back end
I m displaying the datagrid only when the index in the combo box is changed
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
refershGridView(comboBox1.Text);
}
but when I make any updates to the data grid ,the update reflects only after i make a selected index change event
i tried datagidview1.refresh() and also called my refershGridView(comboBox1.Text) functions implicitly
but my grid view refreshes only when i make a selected index change
code for refershGridView(comboBox1.Text)
private void refershGridView(string tableName)
{
saveBttnSwitch = 0;//for save button swicth
//setting back to intial user interface ..
clearVisibilty();
clearall();
button1.Visible = true;
button3.Visible = false;
label11.Visible = false;
try
{
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = ConnString;
//create the database query
string query = null;
if (tableName == "employee")
{
query = "SELECT fname,lname,ssn FROM employee";
dataGridView1.Visible = true;
}
if (tableName == "project")
{
query = "SELECT pname,pnumber FROM project";
dataGridView1.Visible = true;
}
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, mycon);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
try
{
dAdapter.Fill(dTable);
}
catch (OleDbException exp)
{
label11.Text = "file couldnt be found...kindly check Db file location ";
label11.Visible = true;
button1.Visible = false;
}
// DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoGenerateColumns = true;
mycon.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new InvalidOperationException("Data could not be read", ex);
}
this.button2.Visible = false;
}
Does refershGridView(comboBox1.Text); refill the DataGrid?
If so, call it from any other place where you want your data to be refilled. If SelectedIndexChanged even of the combo is the only place you are filling it, it won't refresh unless you change a selection.
And as #Bryan suggests, its better if we see some code.
Try to clear the dTable and dataGridView1.DataSource before you fill the DataTable and sets the DataGridView DataSource
dTable = new DataTable();
dataGridView1.DataSource = nothing;

Categories