Want to Fill Text Box With Access Data - c#

In C# I want to use access data to fill my textBox I Am using ADO.Net To connect to access.So far I've got this:
OleDbConnection con = new OleDbConnection(Price.constr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=con;
cmd.CommandText = "select * from Table1";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Price.constr is my connection String.
I want to fill textBox1 with the data in the Price Column Where my row ID = 1.(For Example)

If you want to read only one record from your table then there is no need to return the whole table and use an adapter to fill a datatable. You can simply ask the database to return just the record you are interested in.
string cmdText = "select * from Table1 WHERE ID = 1";
using(OleDbConnection con = new OleDbConnection(Price.constr))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
textBox1.Text = reader["Price"].ToString();
else
textBox1.Text = "No record found";
}
}
I have enclose the connection, command and reader in an using statement because these are disposable objects and it is a good practice to destroy them when you have finished to use them. (In particular the connection could cause problems if you don't dispose it)
Notice also that I have used the constant 1 to retrieve the record. I bet that you want this to be dynamic and in this case I suggest you to look at how to PARAMETRIZE your queries. (Don't do string concatenations)

Related

Storing multiple values from an SQL select statement

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

Column 'Value' does not belong to table

I have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";

How do i check database table through datatable and extract information of another column of database table?

I was trying to check whether there is any rows having username and friend username in database table. If any then I have to take the friendship status in a string and will return that string.
Here is the code:
string query = "Select * from tblfriend where username = '" + username + "'and friend = '" + friendname + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
rows = dt.Rows.Count;
if (rows > 0)
{
friendship = reader["friendshipstatus"].ToString();
}
But it gives a error message:
Invalid Call to call MetaData when reader is closed.
Can you guys please give a hint?
Since you are loading DataTable from same reader it may be closed after the loading complete.
As Side node, you better use parameters, using statements etc like below
string queryString = "Select [friendshipstatus] from [tblfriend] where [username] = #username and [friend] = #friend";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#friend", friendname );
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if(reader.Read()) // you have matching record if this condition true
{
friendship = reader.GetString(0); // get the value of friendshipstatus
}
}
}
You're using the reader to populate data table and then when it had already been used for that - attempt to use it again.
There are better ways to retrieve single value from db (look up ExecuteScalar) but to make your current code work replace the last line with
friendship = dt.rows[0].["friendshipstatus"].ToString()
This will get the data from the data table you populated instead of closed reader.
You should use dataadapter if you want to read data into table
DataTable dt = new DataTable();
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(query, con))
{
// Use DataAdapter to fill DataTable
a.Fill(dt);
// read data here
}
rows = dt.Rows.Count;
if (rows > 0)
{
friendship = dt.Rows[0]["friendshipstatus"].ToString();
}

display individual columns from sql result in asp.net c#

I'm coding a simple application using c# asp.net. I'm getting the averages of columns. How can I get the individual values from the result and display it in a new label (label1, label2, label3....)?
I tried ExecuteScalar().ToString(); but it returns only the first column.
Below is my code:
SqlConnection con;
con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\STATDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string result = "SELECT AVG(p_tan) AS p_tang, AVG(e_tan) AS e_tang, AVG(p_rel) AS p_reli FROM statistics";
SqlCommand showresult = new SqlCommand(result, con);
con.Open();
Label1.Text = showresult.ExecuteScalar().ToString();
//Label2.Text = p_tang
//Label3.Text = e_tang
//Label4.Text = p_reli
con.Close();
Any help will be appreciated.
Use showresult.ExecuteReader() and then iterate over the row to get the values
SqlDataReader reader=showresult.ExecuteReader();
while (reader.Read())
{
Label1.Text= reader["p_tang"].ToString().Trim();
Label2.Text= reader["e_tang"].ToString().Trim();
Label3.Text= reader["p_reli"].ToString().Trim();
}
ExecuteScalar will only pull one value. You will need do either use a DataReader or DataAdapter to get multiple values from the database.

loading a data table into a data grid view problems

I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;

Categories

Resources