Im trying to populate a text box with infromation that is searched by using a customerID which is inputted throught a text box here is the code im using below
private void txtCustomerID_TextChanged(object sender, EventArgs e)
{
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
txtPoints.Text = sqlPoints;
}
but the text box "txtPoints" only outputs the text of the sqlpoints and not the information in the database? I'm not exactly sure what im doing wrong here.
Any help is appreciated, thanks in advance.
You are not executing the SQL statement on the database. Instead, you are assigning it to txtPoints.Text. You need to execute it on the DB server using, e.g., an OleDbCommand object.
What you need to do instead is something like the following (note this is pseudo-code - I haven't tested it runs)
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn)
// Create a reader containing your results
using(OleDbReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
}
Note also my use of using. This will ensure that your database connections are properly closed once you are finished with them.
Related
Using Visual Studio 2017, I'm trying to build a Windows Forms application that asks a user for specific value from a SQL Server Express database (footballteam).
User enters a value (#jnumber) in a text box (textBox1.Text) which corresponds to the "LIKE" for "JERSEYNUMBER".
Then, the query (commandText) is to be executed after clicking on button (button1_Click)
Results should display a DataGridView.
Build results were: "Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped".
However, when running the application, user enters a number value for #jnumber in textBox.Text, then clicks on button (button1_Click), but dataGridView1 remains empty; no results.
Goal is also to avoid SQL injection. Appreciate your help.
Code is here:
// directives
using System;
using System.Data
using System.Windows.Forms;
using System.Data.SqlClient;
namespace displaydmlquery
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// variable sql query
var commandText = "SELECT * FROM JERSEY WHERE JERSEYNUMBER LIKE '%' + #jnumber+ '%' ORDER BY ASSIGNMENT_DATE";
// variable connection string
var connectionString = "Server=hostname\\SQLEXPRESS;Database=footballteam;User Id=userid;Password=password";
// Create a connection instance
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
// Add the parameter to used in the text box input
command.Parameters.Add("#jnumber", SqlDbType.NVarChar, 20).Value = textBox1.Text;
// Execute query
try
{
// open connection
connection.Open();
// create a SqlDataAdapter to execute query
var dataAdapter = new SqlDataAdapter(commandText, connectionString);
// Create command builder
var commandBuilder = new SqlCommandBuilder(dataAdapter);
// Execute query reader
command.ExecuteReader();
// create a data table to hold query
DataTable dtRecord = new DataTable();
// fill in data tbale
sqlDataAdap.Fill(dtRecord);
// Display results in DataGridView
dataGridView1.DataSource = dtRecord;
}
catch
{
// Handle exception, future code
}
finally
{
connection.Close();
}
}
}
}
}
I was trying to hint at what your problems were in the comments but I failed so I'm taking the time to give you a complete answer.
Below is what your code is doing. You'll notice that some of the lines have question marks. These are the troubling lines because they don't make any sense. It seems you're confusing what the different data objects are meant to do.
1. set up a sql string
2. set up a connection string
3. create a connection Object from connection string from (2)
4. create a command Object from the sql string and the connection object from (1) and (3)
5. set the value of the parameter on the command object from (4)
6. open the connection Object from (3)
7. create a DataAdapter object and a new connection Object (???)
and a new command Object (???) from (1) and (3)
8. create commandBuilder and generate INSERT UPDATE and DELETE commands Objects (???) from the data adapter (7)
9. execute the command object from (4). Disregard the results (???)
10. create a new DataTable Object
11. fill the DataTable from (10) with an unknown sqlDataAdap (does it have
connection, sql, or parameters associated ????)
12. set the DataSource on the datagrid to the filled(?) datatable from (10)
13. throw away exceptions (???)
14. close the connection
15. dispose the connection
Here's some code that should work
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
// Add the parameter to used in the text box input
command.Parameters.Add("#jnumber", SqlDbType.NVarChar, 20).Value = textBox1.Text;
// open connection
connection.Open();
// create a SqlDataAdapter using the command object with the parameters set
var dataAdapter = new SqlDataAdapter(command, connectionString);
// create a data table to hold query
DataTable dtRecord = new DataTable();
// fill in data table with the dataAdapater
dataAdapter.Fill(dtRecord);
// Display results in DataGridView
dataGridView1.DataSource = dtRecord;
} // Using will close the connection when it disposes it
Please try with updating your query
// variable sql query
var commandText = "SELECT * FROM JERSEY WHERE JERSEYNUMBER LIKE '%' #jnumber '%' ORDER BY ASSIGNMENT_DATE";
and add parameter as you are already doing....
I'm trying to figure out how to pull specific Entry lines from an Access Database and into a C# Program.
I'm working with a friend to make a sudoku game. We want to pull different levels of difficulty of puzzles from an access database and into a C# program.
Now my question is: Is there a way to have to program pull the specific lines from the database or would we need to load them all into the program and then have them selected from there? These would be put into a two-dimensional array.
What would be the best way to go about this?
I'm not sure what soduku is, but I'm thinking that you need to query your Access DB. Something like this should get you started.
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
public void PopulateListBoxItems(string userName)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='#1'", connection);
command.Parameters.AddWithValue("#1", userName)
reader = command.ExecuteReader();
while (reader.Read())
{
ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
}
}
}
}
You could use a DataReader as well.
http://www.akadia.com/services/dotnet_data_reader.html
You definitely don't want to pull in all data from a Table; you need to somehow Query the data set.
I am working on a small application for personal use. It is about keeping some data readily available for me.
It just consists of a local database, functions to add, erase or modify 4 or 5 columns of data and displaying the table in a datagridview.
I have managed to add data to the table and I have managed to use a
SELECT * FROM mytable
statement to get the data and iterate through it but I want to bind the table to the datagridview.
Here is my current method of trying to bind the data:
private void button2_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM myTable";
SqlCeConnection conn = new SqlCeConnection(conString);
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, conn))
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
When I run this code it does not throw an exception and if I change the name of the table to something that does not exists then it causes an exception telling that the table does not exists so I know that it is fetching my table. It simply is not showing it.
Any ideas?
Thanks
I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}
You need to call GridView1.DataBind()
GridView1.DataSource = t;
GridView1.DataBind();
Just a side-note, it is good practice to wrap your connection with using
using(con = new System.Data.OleDb.OleDbConnection())
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
...
...
}
This ensures your connection is properly disposed after use
You should use bind function:
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
con.Close();
}
First off, please, please please don't concatenate your WHERE parameters in your SQL. Use Parameters. Second, Add a "using System.Data.OleDb" statement at the top of your module, so that you are not having to type things like:
System.Data.OleDb.OleDbDataAdapter
Over and over again.
Try the following code. Personally, when I have to work with data tables and such, I prefer to avoid all the DataAdapter nonsense, and keep it as simple as possible.
Note in the code below:
the "using" blocks. These place the variables created within them inside their own scope, and take care of disposal and such for you.
I used an OleDb Parameter instead of concatenating criteria. This is a much safer way to do things, and creates much cleaner and more readable code as well, especially in cases where you have several criteria in your WHERE clause.
I assume your UserID input is a string, since you are grabbing the value from a Textbox. If it is in fact an int value (such as an auto-incrementing id in MS Access) you will need to use an int data type instead. You may have to mess with it a little. When you are still figuring this stuff out, it can be a bit painful. However, using parameters increases security and maintainability.
Once you have obtained a data table as the return from the MyUsers method, you should be able to simply set the data source of your Gridview. If you have difficulties still, do as Steve suggests and check the Autogenerate columns property in the designer, or set it in code.
Not that I have moved the connection string to the project Properties/Settings. You should find this in the solution designer. Place your connection string there, in one spot, and you can obtain it from anywhere in your code. If you later change the connection string (such as moving your Db to another computer, server share, etc) you need only change it in one place.
SAMPLE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = #UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("#UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
Hope that helps. It's not how everyone might do it, but I have found it provides maximum flexibility, when you must work with MS Access.
Here is my following code:
string csr = "connection string";
string add = "Insert INTO table (Column1,Column2,Column3) Values (#Column1,#Column2,#Column3)";
using(SqlConnection connect = new SqlConnection(csr))
{
using ( SqlCommand command = new SqlCommand(add,connect))
{
command.Parameters.AddWithValue("Column1",textbox1.text");
//and so on
connect.Open();
command.ExecuteReader();
connect.Close();
}
}
I can see the data added in the gridview but when I check the table data in c# is empty, no value added. what's wrong?
You shouldn't have the connect.Close();, the using statement will take care of that for you.
command.Parameters.AddWithValue("Column1",textbox1.text")
should be
command.Parameters.AddWithValue("Column1",textbox1.text)
Set a breakpoint and ensure your connectionstring was properly set, textbox has a value, etc...