Jut get as result: System.Data.SqlClient.SqlDataReader - c#

Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}

You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}

before execute "executeReader()" then you must read to get results.

Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}

you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...

Related

Fill Combobox with Tables in database c#

How do I fill the combobox with tables (not columns in specific table) in database.
I already did something common like "Data Bound", but when I ran/debug the system, nothing appears in combobox.
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(#"Data Source=USER-PC;Initial Catalog=StudentDB;Integrated Security=True");
string selectQuery = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'";
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString("tables"));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help from experienced developers out there?
the column name is wrong in your code, READER["tables"], the correct column name is TABLE_NAME, try the code below :
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
myComboBox.Items.Clear();
while (reader.Read())
{
myComboBox.Items.Add((string) reader["TABLE_NAME"]);
}
}
}
}

Invalid attempt to call Read when reader is closed

I am having a problem with the sql datareader. Whenever I try to read data it gives me an error saying invalid attemp to call Read when the reader is closed. Please help me figure out the problem
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Gardezi\Documents\Visual Studio 2012\Projects\homeWork2\homeWork2\Database1.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(connstring);
string query = "Select * from diaryDB";
SqlCommand com = new SqlCommand(query, con);
SqlParameter p = new SqlParameter("name", name);
con.Open();
SqlDataReader d = com.ExecuteReader();
con.Close();
deleteResult r = new deleteResult(d);
r.Show();
}
this is the constructor of deleteResult
public deleteResult(SqlDataReader d)
{
InitializeComponent();
while (d.Read())
{
this.comboBox1.Items.Add((d["Title"] +"-" +d["Description"]).ToString());
}
}
You can't read after closing the connection.
Just change this part of your code:
FROM
(...)
con.Close();
deleteResult r = new deleteResult(d);
(...)
TO
(...)
deleteResult r = new deleteResult(d);
con.Close();
(...)
Please try to use the using statement that correctly enclose the connection, the command and the reader in appropriate blocks.
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"....";
string query = "Select * from diaryDB";
using(SqlConnection con = new SqlConnection(connstring))
using(SqlCommand com = new SqlCommand(query, con))
{
SqlParameter p = new SqlParameter("name", name);
con.Open();
using(SqlDataReader d = com.ExecuteReader())
{
deleteResult r = new deleteResult(d);
r.Show();
}
}
}
In this way the connection is kept open while you read from the reader. This is essential to avoid the error.
The more important point is that you don't have to worry to close and dispose the connection when it is no more needed. The exit from the using block close and dispose the connection, the command and the reader ALSO in case of exceptions.

Receiving the error "ExecuteReader requires an open and available Connection. The connection's current state is closed." when running my application

I am trying to display some values in textboxes from a database by selecting a site ID from a drop down list. The drop down list is working perfectly and showing the site IDs that are stored in the database. While running this application it shows an error:
Execute Reader requires an open and available Connection. The connection's current state is closed.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOption();
}
}
private void LoadOption()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(#"connectionString");
using (con)
{
SqlDataAdapter adpt = new SqlDataAdapter("SELECT Site_ID FROM tbl_Survey1", con);
adpt.Fill(dt);
ddlSiteID.DataSource = dt;
ddlSiteID.DataTextField = "Site_ID";
ddlSiteID.DataValueField = "Site_ID";
ddlSiteID.DataBind();
ddlSiteID.Items.Insert(0, new ListItem("--Select ID--", ""));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
Source:
<asp:DropDownList ID="ddlSiteID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlSiteID_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="txtSiteName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSiteAddress" runat="server"></asp:TextBox>
The error explains all. Your connection is closed when you call ExecuteReader. But I suppose that you are asking why?.
You think that, because you have already loaded the dropdown, then you could execute your reader without problems. But, unfortunately, the SqlDataAdapter has its own behavior when working with the connection.
From MSDN SqlDataAdapter.Fill
The Fill method retrieves rows from the data source using the SELECT
statement specified by an associated SelectCommand property. 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.
So you just need to open the connection in this way
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
string selectID = ddlSiteID.SelectedValue;
using(SqlConnection con = new SqlConnection(#"connectionString"))
using(SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
....
}
}
}
P.S. Remember to keep always your disposable objects like the connection, command and reader inside an Using block to be sure that they are closed and disposed correctly also in case of exceptions
You're missing in the second method an explicit call to open your connection:
con.Open();
Also, you don't dispose of said connection -- be careful with that. Use usings for anything that implements IDisposable:
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"connectionString"))
{
con.Open();
string selectID = ddlSiteID.SelectedValue;
using (SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
}
You should open your connection by calling con.Open() before calling ExecuteReader in ddlSiteID_SelectedIndexChanged method. And don't forget to close it in the end.
This means your code may look like
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
using(var con = new SqlConnection(#"connectionString"))
{
string selectID = ddlSiteID.SelectedValue;
using (var cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con))
{
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
finally
{
con.Close();
}
}
}
}
try this In SelectedIndexChanged event of DropDown.
SqlCommand requires Connection to be open
SqlConnection con = new SqlConnection(#"connectionString");
string selectID = ddlSiteID.SelectedValue;
SqlCommand cmd = new SqlCommand("SELECT Site_Name,Site_Address FROM tbl_Survey1 where Site_ID=#Site_ID", con);
cmd.Parameters.AddWithValue("#Site_ID", selectID);
cmd.CommandType = CommandType.Text;
con.open
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
txtSiteName.Text = rdr.GetString(0);
txtSiteAddress.Text=rdr.GetString(1);
}
}
}
}
con.close();
Check if your connection is open or not.
if (con != null && con.State == ConnectionState.Closed)
{
con.Open();
}

Read data from Access Database into listbox

Can someone tell me how to fix this error?
SqlCommand cmd = new SqlCommand(sqlCmd, conn)
--> conn: Aurgument type 'System.Data.OleDb.OleDbConnection' is not assignable to parameter type 'System.Data.SqlClient.SqlConnection'.
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
SqlCommand cmd = new SqlCommand(sqlCmd, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You're mixing up Sql and OleDb
Use OleDbCommand instead of SqlCommand
and use OleDBDataReader instead of SqlDataReader
For example:
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);
using (OleDBDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You are using SqlCommand/etc which requires the use of SqlConnection object instead of OleDbConnection.
Is it a SQL database you are connecting to? If so use SqlConnection instead
Edit: Obviously not, reading the connection string ... :D

How to bind a datasource to a label control

It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The query I'm using:
SELECT Description FROM RbSpecials WHERE Active=1
public string SqlConnection(string queryString)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = queryString;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// This will return the first result
// but there might be other
return reader.GetString(0);
}
}
return null;
}
}
This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.
And finally assign the Text property of the label:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");
use ExecuteReader rather than ExecuteNonQuery
public void Sql_Connection(string queryString)
{
using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings"RBConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand(queryString, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
lblDescription.Text = rdr.GetString(0);
}
}
}
}
}
using (SqlConnection con = new SqlConnection(Connection_String))
{
SqlCommand cmd = new SqlCommand("select * from Customers", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader adpt = cmd.ExecureReader();
if(rdr.Read())
{
lblName.Text = rdr[0].ToString();
}
}

Categories