Good afternoon all,
I was hoping someone can point me in the right direction with this. I am currently working on a project and I am using an Access file as a database. I am trying to figure out how to populate items in my combobox from the different tables I have inside of my access database. I am using C# and Access 2016. I have tried to use some other examples and found that I am not looking in the right direction.
Edit:
I may have been a bit vague in this question. I have around 7 tables all with different names "ESC,AJJH,etc." in a Access file and I need to have the table names populate my combobox so when the user selects the combo box they can manipulate the data that's within the selected table. I hope this is more clear, I apologize if not.
Thank you!
private void Form1_Load(object sender, EventArgs e)
{
using (var connection = new OleDbConnection())
{
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb;Jet OLEDB:Database Password = MyDbPassword;";
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Tables";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
schoolcombo.Items.Add(reader);
}
}
catch (Exception ex)
{
MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
}
}
You can use DbConnection. GetSchema to get the list of tables.
display the list of tables in access database using c#
It is not so clear what you want. But supposing that your tables have the same kind of columns. You could make use of UNION statement:
string query = "select field1, field2 from Table1 UNION select field1, field2 from Table2"; //AND SO ON
Related
I saw many many articles on this but none helped so far.
My ComboBox name is cbPlan. I want to Retrieve PlanName in it's display but want to actually hold it PlanID.
Following code displays both Names and IDs. I tried ValueMember, DisplayMember, properties but couldn't get it sorted yet.
Finally, even if this works out, how will I get to insert PlanID in another table? Will i use Convert.ToString(cbPlan.Text) - which would bring the PlanName and not the ID.
Please help on this - A big thank you in advance! :)
P.S. PlanID's data type is int.
private void cbPlan_Click(object sender, EventArgs e)
{
cbPlan.Items.Clear();
string pullsub = "select PlanID,PlanName from fbkPlanMaster(nolock)";
string connString = ConfigurationManager.ConnectionStrings["Dbconn"].ToString();
SqlConnection connection = new SqlConnection(connString); // defining sql connection
SqlCommand cmd = new SqlCommand(pullsub, connection);
cmd.CommandText = pullsub;
connection.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
cbPlan.Items.Add(drd["PlanID"]);
cbPlan.Items.Add(drd["PlanName"]);
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
}
}
First of all modifying your approach to add items to your combo-box you should not use Reader. Second, why are you adding PlanID if you don't want to display it?
This code may help you ...
cbPlan.DataSource = dt;
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
You should first get your data from database into some datatable or a dataset as above cbPlan.DataSource = dt;
This will hold your id as ValueMember as an ID and its displayed text will be PlanName. Hope this helps you.
Here I am trying to load the dropdownlist box from a column of a table in Mysql(which contains repeated values), so I need to get unrepeated values.
This is my code:
MySqlConnection cn = new MySqlConnection("Connection String");
MysqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
cmd = cn.createcommand();
cmd.CommandText = "Select Columnname from tablename";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DropDownList.Items.Add(reader.GetString("Columnname"));
}
}
cn.close();
}
Try editing your SQL query to get DISTINCT results
cmd.CommandText = "SELECT DISTINCT Columnname FROM tablename";
The code snippet is then presumably called more than once, maybe on each post back. Just clear the items first:
DropDownList.Items.Clear();
One thing to note is that when ViewState is enabled there is no need to reload your drop down lists on each subsequent post back. That also means that you can decide rather to execute this code only if if (!this.IsPostBack)`.
table1:
id name
1 saravanan
2 karumbasalam G
3 saravanan
select distinct name from table1
output:
name
saravanan
karumbasalam G
Use the distinct keyword used to avoid duplicates
I am using sql server 2012 and visual studio 2010 and what I have so far is a single table int the database and a small c# application that loads the employees into a datagridview
however what I want to do is select only employees with the job title 'Waiter'
So far i have written queries on adding records editing deleting and displaying the whole data.
So far I have managed to display the names only by reading a specified column:
private void LoadEmpName()
{
sc.Close();
try
{
sc.Open();
cmd.CommandText = "select * from myEmployees";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lstNames.Items.Add(dr[1].ToString());
}
}
sc.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Is it possible to change my existing code so that only employees that are listed as 'Waiter' are displayed (first name only) or will i have to write a totally different query?
You should add a where clause to your SQL query. I don't know your database structure, but something like;
cmd.CommandText = "select * from myEmployees where title='waiter'";
It is much more efficient to do your filtering in SQL rather than in C#.
If you have a column called "JobTitle" then your query would become:
"select * from myEmployees where JobTitle like '%waiter%'";
The "like" is the comparison operator and the "%" is a wildcard of any number of characters.
There are several ways you could go if you want queries for different things. The simplest is to simply create a new method that has the part time test in the query string:
"select * from myEmployees where PartTime = 1";
However, you will need a new query for each possible search the user could do and this would become inefficient to maintain.
As you are populating a data grid you should look at doing the filtering in the client. You bring all the data (using paging if you have a large amount) and then let the user decide what information they are interested in seeing by specifying their own filters.
select * from myEmployees where jobtitle='Waiter'
Discalimer: The OP asked "Is it possible to change my existing code so that only employees that are listed as 'Waiter' are displayed (first name only) or will i have to write a totally different query?"
So purely to answer that you don't 'have' to use a new query. You could place an if before you add like this(assuming your second column is 'job title'):
while (dr.Read())
{
if(dr[2].ToString().EqualsIgnoreCase("Waiter")){
lstNames.Items.Add(dr[1].ToString());
}
}
Although I would not recommend it.
you will have to change the query . It is better approach.
I liked #CrisF solution. just addition to it.
private void LoadEmpName()
{
try
{
sc.Open();
//it will return all employees containing word waiter in Column JobTitle.
cmd.CommandText = "select * from myEmployees where JobTitle like '%waiter%' ";
dr = cmd.ExecuteReader();
while (dr.Read())
{
lstNames.Items.Add(dr[1].ToString());
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sc.Close();
}
}
I'm trying to learn some C#.net. I'm just trying to expose the AdventureWorks database included in my C# class via a web interface. Here's the setup:
I've got a DropDownList in on my ASPX page with an id of tableNameDropDown. It gets populated on Page_Load like this:
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
String table_names_sql = "select Name from sysobjects where type='u' ORDER BY name";
SqlCommand cmd = new SqlCommand(table_names_sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tableNameDropDown.Items.Add(reader[0].ToString());
}
conn.Close();
tableNameDropDown.AutoPostBack = true;
}
And that works just fine, I get a nice long list of the tables in the DB. When someone selects a table from the list, I want to display that table in a GridView control with an id of grid. This is what I've got:
protected void tableNameDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dataSet = new DataSet();
String tableName = columnNameDropDown.SelectedItem.ToString();
String table_sql = String.Format("SELECT * FROM {0};", tableName);
SqlDataAdapter adapter = new SqlDataAdapter(table_sql, conn);
adapter.Fill(dataSet, tableName);
grid.DataSource = dataSet;
grid.DataMember = tableName;
}
When I debug the page, I get an error on the adapter.Fill(dataSet, tableName); line: SqlException: Inlvalid object name '{tableName}'.
The tables in the DB are the following:
dbo.AWBuildVersion
.... more dbo. tables
HumanResources.Department
HumanResources.Employee
.... more HumanResources tables
Person.Address
Person.AddressType
.... more Person tables
... Other prefixes are "Pdoduction, Purchasing, Sales"
There are probably ~50+ tables, and I get all their names (without the prefixes) into my DropDownList no problem, but I can't seem to query them.
Any ideas?
You've already answered yourself: you need to use also the prefix in the select statement you're executing, like
Select * From Person.Address
Beside that you should not use the sysobject tables, from SQL Server 2005 you have system views that helps you, so you can write a better statement to select tables:
select * From INFORMATION_SCHEMA.TABLES
Check also this article.
Regards
Massimo
Ok, so here's the problem I have to solve. I need to write a method in C# that will modify a table in SQL Server 2008. The table could potentially contain millions of records. The modifications include altering the table by adding a new column and then calculating and setting the value of the new field for every row in the table.
Adding the column is not a problem. It's setting the values efficiently that is the issue. I don't want to read in the whole table into a DataTable and then update and commit for obvious reasons. I'm thinking that I would like to use a cursor to iterate over the rows in the table and update them one by one. I haven't done a whole lot of ADO.NET development, but it is my understanding that only read-only server side (firehose) cursors are supported.
So what is the correct way to go about doing something like this (preferably with some sample code in C#)? Stored procedures or other such modifications to the DB are not allowed.
jpgoody,
Here is an example to chew on using the NerdDinner database and some SQLConnection, SQLCommand, and SQLDataReader objects. It adds one day to each of the Event Dates in the Dinners table.
using System;
using System.Data.SqlClient;
namespace NerdDinner
{
public class Class1
{
public void Execute()
{
SqlConnection readerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
readerConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT DinnerID, EventDate FROM Dinners", readerConnection);
SqlDataReader reader = cmd.ExecuteReader();
SqlConnection writerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
writerConnection.Open();
SqlCommand writerCommand = new SqlCommand("", writerConnection);
while (reader.Read())
{
int DinnerID = reader.GetInt32(0);
DateTime EventDate = reader.GetDateTime(1);
writerCommand.CommandText = "UPDATE Dinners SET EventDate = '" + EventDate.AddDays(1).ToString() + "' WHERE DinnerID = " + DinnerID.ToString();
writerCommand.ExecuteNonQuery();
}
}
}
}
Your problem looks like something that you should be solving using T-SQL and not C#, unless there is some business rule that you are picking up dynamically and calculating the column values T-SQL should be the way to go. Just write a stored procedure or just open up Management studio and write the code to make your changes.
If this does not help then please elaborate on what exactly you want to do to the table, then we can help you figure out if this can be done via T-SQL or not.
[EDIT] you can do something like this
string sql = " USE " + paramDbName;
sql+= " ALTER TABLE XYZ ADD COLUMN " + param1 + " datatype etc, then put semicolon to separate the commands as well"
sql+= " UPDATE XYZ SET Columnx = " + some logic here
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
get this executed on the required instance of Sql Server 2008.
If you have too many lines of text then use StringBuilder.
Here's a suggestion:
You can read data using a DataReader , create a update command for current row and add it to a list of commands.Then run update commands in a transaction.
something like this:
var commands=new List<SqlCommand>();
while(dr.Read())
{
var cmd=new SqlCommand();
cmd.CommandText="Add your command text here";
commands.Add(cmd);
}
using(var cnn=new SqlConnection("Connection String"))
{
IDbTransaction transaction;
try
{
cnn.Open();
transaction=cnn.BeginTransaction();
foreach(var cmd in commands)
{
cmd.Transaction=transaction;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
transaction.Commit();
}
catch(SqlException)
{
if(transaction!=null)
transaction.Rollback();
throw;
}
}