I want to add data from my Access database to a label. the data was searched using a query on FORM1.
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ty\Documents\Uni\Level6\Project\App\software\Databases\Boards.accdb;Persist Security Info=False;";
connection.Open();
OleDbCommand commandBoards = new OleDbCommand();
commandBoards.Connection = connection;
string queryBoardsLength = "select * from [Boards] where [Length] >=" + TxtLength.Text;
string queryBoardsWidth = "select * from [Boards] where [Width] >=" + TxtWidth.Text;
commandBoards.CommandText = queryBoardsLength;
commandBoards.CommandText = queryBoardsWidth;
OleDbDataReader readerBoards = commandBoards.ExecuteReader();
while (readerBoards.Read())
{
ComBoards.Items.Add(readerBoards["ID"].ToString());
}
this populated a combo box on FORM1 with the search results. I then set the selected result from the combo box as a variable when it is selected.
private void ComBoards_SelectedIndexChanged(object sender, EventArgs e)
{
Boards = this.ComBoards.GetItemText(this.ComBoards.SelectedItem);
}
On FORM2 I ran a similar query to gather the exact data from the Access database based on the selected ID. I want to display the length as a label.
private void Form2_Load(object sender, EventArgs e)
{
lblBoardname.Text = Form1.Boards;
OleDbConnection connectionBoards = new OleDbConnection();
connectionBoards.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ty\Documents\Uni\Level6\Project\App\software\Databases\Boards.accdb;Persist Security Info=False;";
connectionBoards.Open();
OleDbCommand commandBoardsget = new OleDbCommand();
commandBoardsget.Connection = connectionBoards;
string queryBoardsget = "select * from [Boards] where [ID] =" + lblBoardname;
commandBoardsget.CommandText = queryBoardsget;
OleDbDataReader readerBoardsget = commandBoardsget.ExecuteReader();
while (readerBoardsget.Read())
{
lblBoardsizel.Text = readerBoardsget["Length"].ToString();
}
Everything works apart from the Reader on FORM2 where I get the following error:
Syntax error (comma) in query expression '[ID]=System.Windows.Forms.Label, Text: Rhino Boards'.
I would really appreciate some help. Thanks.
Related
I'm learning C# for a small project with an Access DB.
I get no error when I click on the button to run my sql statement through OleDbCommand but no row is inserted in the table though.
I think my connection is perfectly set up because I get an error if I don't use the right type for a column (e.g. insert a string in an int).
I know the button is working too because I add an action on a text which is working. Finally I know also that my query works since I have tried it directly via VS on my table.
Am I missing a step?
Here my code:
namespace ProjetFalk
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btn_onclick_Click_1(object sender, EventArgs e)
{
label12.Text = string.Empty;
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=DBFalk.accdb";
OleDbConnection dbconn = new OleDbConnection(connectionString);
dbconn.Open();
string dbcommand = "INSERT INTO Produit (NOM,REFERENCE) VALUES('TEST2', 'test2')"; // + TextBox_Nom.Text + "')";
OleDbCommand cmd = new OleDbCommand(dbcommand, dbconn);
cmd.ExecuteNonQuery();
dbconn.Close();
}
}
}
Please be tolerant, it's new for me. (I have read the docs on Microsoft too for my setup)
I'll start off by saying that I'm pretty inept at coding (have yet to learn how to utilize classes and how they work in depth), and that I've never worked with sql before doing this project.
The idea here is that you connect to an sql database, after which a datagridview element gets filled with data from a table called TABLE_1 by default. The user should then be able to input, delete and save data.
The first two work operations work perfectly, but the saving is the problem. I've banged my head against a wall for about 4 days trying to get the saving to work, but I just cant get it to do so. The saving is done with the method Button3_click.
Any insight as to what I should do?
Is the main chunk of the code where you connect the part where I'm
messing up?
//initialize the classes I guess, on some youtube guides they did so
SqlConnection con;
DataSet ds;
SqlDataAdapter a;
DataTable t;
SqlCommandBuilder scb;
static string tablename = "TABLE_1";
string constring;
//connect button
private void button1_Click(object sender, EventArgs e)
{
try
{
//connect using info from textboxes, connection is ok
constring = "server=" + Server.Text + ";database=" + DB.Text + ";UID=" + UID.Text + ";password=" + Password.Text;
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
Save.Enabled = true;
//check if table name is empty, if so default to TABLE_1
if (textBox1.Text != "")
{
tablename = textBox1.Text;
}
else
{
tablename = "TABLE_1";
}
a = new SqlDataAdapter("SELECT * FROM " + tablename, con);
DataTable t = new DataTable();
a.Fill(t);
datagrid.DataSource = t;
//
label5.Text = Server.Text;
con.Close();
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
//save button
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
DataTable t = new DataTable();
a.TableMappings.Add(tablename, "t");
scb = new SqlCommandBuilder(a);
a.Update(t);
con.Close();
}
Use the following example which sets up the adapter, dataset and table name as private variables.
Also, I recommend to never use one letter variable names as a) it's difficult to debug b) when getting into more lines of code it's going to be difficult to know what a variable is for.
Next up, using SELECT *, it' unknown if you have setup a auto-incrementing primary key which is needed to perform updates. In the example below, Id is auto-incrementing.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsDataAdapterExample
{
public partial class Form1 : Form
{
private SqlDataAdapter _companiesSqlDataAdapter;
private DataSet _companiesDataSet;
private string _tableName = "Companies";
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
_companiesDataSet = new DataSet();
_companiesSqlDataAdapter = new SqlDataAdapter(
"SELECT Id, FirstName, LastName, PhoneNumber, City FROM dbo.Companies;",
"Data Source=.\\sqlexpress;Initial Catalog=ForumExample;" +
"Integrated Security=True");
var builder = new SqlCommandBuilder(_companiesSqlDataAdapter);
_companiesSqlDataAdapter.Fill(_companiesDataSet, _tableName);
dataGridView1.DataSource = _companiesDataSet.Tables[_tableName];
}
private void SaveButton_Click(object sender, EventArgs e)
{
_companiesSqlDataAdapter.Update(_companiesDataSet, _tableName);
}
}
}
Hey Im new to stacoverflow and would like to ask some help. I need to type a ID into a textbox and when searched is clicked it will find the record and display each of the colum values to text boxes. Im using a access database. I have found solution on this but they dont seem to work. I have found and ajusted the following code but give an error op conn.open() and is coded in C#. Please help me.
source Code:
public partial class FamilyTree : UserControl
{
private OleDbConnection conn;
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void ConnectToDatabase()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb");
conn.Open();
}
private void DisconnectDatabase()
{
conn.Close();
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
string queryString = "SELECT * FROM FamilyTree" + txtID ;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = conn;
conn.Open();
OleDbDataReader dr = command.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
conn.Close();
}
Ensure that the 'ConnectToDatabase()' method is called somewhere before using 'conn' in btnSearch_Click.
Next, decide whether you are using the Id or Title to filter the result.
When creating the queryString, ensure you use the 'WHERE Id = ' or 'WHERE Title = ' clause to filter - but also ensure that you have a space between the end of the queryString and the value added at the end - the example you have given would produce 'SELECT * FROM FamilyTree23' if the Id was 23. This would error because there is no table with this name in the database.
Finally, as mentioned in other answers, 'using' a database connection, and using query parameters are a better practice. The 'using' statement will release the connection automatically after use, and a parameterised query prevent will SQL Injection issues and ensure correct data types are passed to the query.
Example:
public partial class FamilyTree : UserControl
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb";
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
sqlQuery = "SELECT * FROM FamilyTree WHERE Title = ?";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Title", title);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
}
}
}
}
I try to get the names of SQL databases in the server in this code I listed all sql instances in my computer in a combobox named sever using sqldatasource enumerator now I am trying to get the names of all sql databases names in the another combobox when I select a specific sql instance from server combobox but it doenot work
private void Connect_Load(object sender, EventArgs e)
{
sqlservertable = sqlenumeratotr.GetDataSources();
server.DataSource = sqlservertable;
server.DisplayMember = sqlservertable.Columns["servername"].ToString();
server.ValueMember = sqlservertable.Columns["servername"].ToString();
}
private void server_SelectedIndexChanged(object sender, EventArgs e)
{
servername = server.SelectedValue.ToString();
constring = "server=servername;Integrated Security = sspi";
SqlConnection con = new SqlConnection(constring);
con.Open();
dbltables = con.GetSchema("Databases");
con.Close();
databases.DataSource = dbltables;
databases.DisplayMember = dbltables.Columns["database_name"].ToString();
}
If I understand the question correctly, I think that Heather's answer sufficiently addresses the question, I'll expand on it a bit.
You'll need to run the query that Heather mentioned, and then bind the results to the other ComboBox.
private void server_SelectedIndexChanged(object sender, EventArgs e)
{
string serverName = server.SelectedValue.ToString();
string connString = string.Format("server={0};Integrated Security = sspi", serverName);
using (var con = new SqlConnection(connString))
{
using (var da = new SqlDataAdapter("SELECT Name FROM master.sys.databases", con))
{
var ds = new DataSet();
da.Fill(ds);
databases.DataSource = ds.Tables[0].Rows.Select(x => x["Name"].ToString());
//...
}
}
}
select name from master.sys.databases
I try to get one data column from a MS-Access table and display it in a TextBox like this
public partial class Form1 : Form
{
public OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private OleDbConnection Database_Connection;
private void Open_Database_button_Click(object sender, EventArgs e)
{
Database_Connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb");
OleDbCommand Command = new OleDbCommand(
" SELECT top 1 * from test", Database_Connection);
Database_Connection.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
// How can I display the column in TextBox?
}
...
}
Try to change your Open_Database_button_Click in this way:
private void Open_Database_button_Click(object sender, EventArgs e)
{
using(OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb" ))
using(OleDbCommand Command = new OleDbCommand(" SELECT top 1 * from test", con))
{
con.Open();
OleDbDataReader DB_Reader = Command.ExecuteReader();
if(DB_Reader.HasRows)
{
DB_Reader.Read();
textbox1.Text = DB_Reader.GetString("your_column_name");
}
}
}
What I have changed/added:
Removed the global var DataBase_Connection
Added using to the Disposable objects, so they will automatically
closed when no more needed
Added check on DB_Reader.HasRows to exclude empty results from the
query
Added setting of the text property of the textbox with the value of
one of your columns