How to display a specific data from a database into textbox? - c#

public DataTable DisplayHolidays(int empid)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("ComputeHoliday", myCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = empid;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
temp2 = rd[0].ToString();
}
return dt;
}
This is my code I had a problem/error with this part. This code is in the class not in the form load. It cannot display the data in the textbox. I'm using temp2 to store the data in the selected row but it's not yet working.

I assume that you're getting an exception at cmd.ExecuteReader().
Note that you must open the connection before you can use the command in cmd.ExecuteReader(). DataAdapter.Fill does not need an open connection, the dataadapter will open/close it implicitly.
MSDN:
The connection object associated with the SELECT statement must be
valid, but it does not need to be open. If the connection is closed
before Fill is called, it is opened to retrieve data, then closed. If
the connection is open before Fill is called, it remains open.
Why do you use DataAdapter.Fill(DataTable) and also Command.ExecuteReader? You need just one way to get the data. If you already have filled a table:
If(dt.Rows.Count > 0)
{
temp2 = dt.Rows[0].Field<string>(0);
}
If you don't use the DataAdapter and the DataTable but only the reader:
using(SqlDataReader rd = cmd.ExecuteReader())
{
if(rd.HasRows)
{
rd.Read();
temp2 = rd.GetString(0);
}
}

Related

creating a list which works as inparameter for gridview

I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand
(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue
(
"#companyName",
textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.

Want to Fill Text Box With Access Data

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)

Don't close SQL connection until is has finished reading

I have the below code, which works, but is only reading the top row of the DB and then terminating. The array should hold 3 pieces of data, but it only holds one.
I think this is because it is not looping.
How do you say for the code to carry on running until it has no more data to read?
SqlConnection conn1 = new SqlConnection(ssConnectionString);
conn1.Open();
SqlCommand command1 = conn1.CreateCommand();
command1.CommandText = "SELECT FeedURL FROM [dbo].[Feeds]";
rssFeeds.Add(command1.ExecuteScalar());
conn1.Close();
By default ExecuteScalar() will only ever return one value. You would need to create a DataReader, and then loop through the results using command1.ExecuteReader()
conn1.Open();
string query = "select feedurl from [dbo].[feeds]";
DataSet DS = new DataSet();
SqlDataAdapter adapt = new SqlDataAdapter(query,conn1);
adapt.Fill(DS);
if (DS != null)
{
if (DS.Tables[0].rows.Count > 0 )
{
foreach(DataRow DR in DS.Tables[0].Rows)
{
string temp = DR['columnname'];
}
}
{
You can just use ExecuteReader for your problem. In this example that I took from MSDN is consuming the connection with using statement because SqlConnection class has some unmanaged resources. If you have more questions about using and Finalizers also check here.
How to use ExecuteReader, you can check here:
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
Try this:
//method to make this code reusable
//the returned data set is accessible even if the underlying connection is closed
//NB: that means data's held in memory; so beware of your resource usage
public DataSet ExecuteSQLToDataSet(string ssConnectionString, string query, string name)
{
DataSet ds = new DataSet("Tables");
using (SqlConnection conn1 = new SqlConnection(ssConnectionString))
{
conn1.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, objConn);
sda.FillSchema(ds, SchemaType.Source, name);
sda.Fill(ds, name);
} //using statement will close and dispose the connection for you
return ds;
}
//example usage
DataSet ds = ExecuteSQLToDataSet(ssConnectionString, "SELECT FeedURL FROM [dbo].[Feeds]", "Feeds"); //nb: name doesn't have to match table name; you can call it what you like; naming is useful if you wanted to add other result sets to the same data set
//DataTable tblFeeds = ds.Tables["Feeds"]; //if you want to access the above query by name
foreach (DataTable tbl in ds.Tables)
{
foreach (DataRow dr in tbl.Rows) //tblFeeds.Rows if you did that instead of looping through all tables
{
//Console.WriteLine(dr["FeedURL"].ToString()); //you can specify a named column
Console.WriteLine(dr[0].ToString()); //or just use the index
}
}
Console.WriteLine("Done");
Console.ReadLine();
More Detail: http://support.microsoft.com/kb/314145

ADO.NET - DataRead Error

I am trying to display data from a column in my database onto my rich textbox, but I am getting mixed up between DataSet and DataReader - I know the majority of the code below is correct, I just get two lines containing errors, and I'm not sure why:
// Create a connection string
string ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Documents and Settings\\Harley\\Desktop\\Test.accdb");
string SQL = "SELECT * FROM Paragraph";
// create a connection object
SqlConnection conn = new SqlConnection(ConnectionString);
// Create a command object
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt); //ERROR
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
foreach(DataRow reader in dsRtn) //ERROR
{
richTextBox = richTextBox.Text + reader[0].ToString();
}
//Release resources
reader.Close();
conn.Close();
}
Each of your snippets has an issue.
For the Data Adapter implementation you provided this:
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt); //ERROR
You are not associating your SqlCommand object with your DataAdapter so it has no idea how to fill your DataTable.
As for your Data Reader implementation,
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
foreach(DataRow reader in dsRtn) //ERROR
{
richTextBox = richTextBox.Text + reader[0].ToString();
}
you are using the DataReader incorrectly try this:
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
while( reader.Read() )
{
richTextBox = richTextBox.Text + reader[0].ToString();
}

How to populate a gridview with table data from sql

I want to populate a gridview with table data from SQL. I tried just returning my SqlDataReader object and using it as my datasource, but I am getting errors that the reader has been closed. I wanted to convert this to a DataSet and just return a dataset, but I couldn't find an easy way to convert the row data to a dataset. I've also read that DataSets are dead in .NET 3.5/4.0, is this true?
Here's my Data Layer method. It would be awesome if I could return something useable as a datasource:
public SqlDataReader GetSites()
{
SqlConnection sqlCon = null;
SqlDataReader rdr = null;
try
{
sqlCon = new SqlConnection(StoredProcedures.conString);
sqlCon.Open();
SqlCommand cmd = new SqlCommand("GetSites", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
return rdr;
}
finally
{
if (sqlCon != null)
{
sqlCon.Close();
}
//if (rdr != null)
//{
// rdr.Close();
//}
}
}
As Carlos Munoz has stated, you closed your sql connection. You need the SQL connection opened in order for the reader to read. Simply comment out
if (sqlCon != null)
{
sqlCon.Close();
}
and you should be fine.
Another alternative is to use SqlDataAdapter which I prefer.
Here is an example...
public static DataSet GetDataSet(string sql, DatabaseType database)
{
using ( var connection = new SqlConnection( GetConnectionString(database) ) )
{
using (var adapter = new SqlDataAdapter(sql, connection))
{
var temp = new DataSet();
adapter.Fill(temp);
return temp;
}
}
}
Just set the data source of your data grid to the Data set's table returned.
DGV.DataSource = DatabaseFunction.GetDataSet(sql, DatabaseType.Outage).Tables[0].DefaultView;
I suggest using a Typed-Dataset with typed table adapters. Add a new Typed-DataSet into your project and drop the tables from the server explorer in visual studio directly into your typed-dataset and configure it. You can then use that type dataset as the datasource of your datagrid
dataAdapter = new SqlDataAdapter(sqlQuery, DatabaseConnectionString);
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
builder.GetUpdateCommand();
dataSet = new DataSet();
DataAdapter.Fill(dataSet);
dataGridView.DataSource = dataSet.Tables[0];
SqlCommandBuilder should be used if you want to update changes made in dataGridView back to SqlDatabase! Than you can write:
dataAdapter.Update(dataSet);
If you want to use new stuff, you can generate object model that corresponds to you SqlDatabase with SqlMetal tool. This will generate classes that have members as tables is your dataabse. After that you use LINQ query that is used as datasource of you dataGeidView.

Categories

Resources