I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result
Related
Disclaimer - yes I googled, clearly I didn't find a solution.
Webform, ASP.NET, SQL, no sqldatasource - all codebehind.
Ok, looks like I was misunderstanding what was going wrong in my application.
Using .SelectedValue does get the correct value of the drop down item - but only in my Insert() method, .SelectedValue returns empty in my UpdateMethod.
Insert()
using (con = new SqlConnection(conString))
{
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Building(Building_Code, Building_Name, Company_ID, Active) VALUES(#BuildingCode, #BuildingName, #CompanyID, #Active)", con);
cmd.Parameters.AddWithValue("#BuildingCode", txtBuildingCode.Text);
cmd.Parameters.AddWithValue("#BuildingName", txtBuildingName.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
cmd.Parameters.AddWithValue("#Active", chkBuildingActive.Checked);
cmd.ExecuteNonQuery();
}
Update()
using (con = new SqlConnection(conString))
{
try
{
if (ddlCompanyCode.SelectedIndex >= 1)
{
con.Open();
cmd = new SqlCommand("UPDATE Building SET Building_Name = #BuildingName, Company_ID = #CompanyID, Active = #Active WHERE Building_ID = #BuildingID", con);
cmd.Parameters.AddWithValue("#BuildingID", selectedRecordID);
cmd.Parameters.AddWithValue("#BuildingName", txtBuildingName.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
cmd.Parameters.AddWithValue("#Active", chkBuildingActive.Checked);
cmd.ExecuteNonQuery();
}
}
catch (SqlException sqlExc)
{
MessageBox.Show(sqlExc.Message);
}
}
BindForm()
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtBuildingCode.Text = reader["Building_Code"].ToString();
txtBuildingName.Text = reader["Building_Name"].ToString();
ddlCompanyCode.SelectedItem.Text = reader["Company_Code"].ToString();
chkBuildingActive.Checked = reader.GetBoolean(reader.GetOrdinal("Active"));
}
}
catch (SqlException sqlExc)
{
MessageBox.Show(sqlExc.Message);
}
What would cause this issue?
Instead using ddlCompanyCode.DataValueField use SelectedValue property
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
You can as well use SelectedItem.Value like
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedItem.Value);
Woo! I got a solution from a friend.
Create a local variable for the company code value
string strCompany = "";
Read the contents of the datareader to the variable
txtBuildingCode.Text = reader["Building_Code"].ToString();
txtBuildingName.Text = reader["Building_Name"].ToString();
strCompany = reader["Company_Code"].ToString();
Then set the SelectedIndex of the drop down to the item index by
ddlCompanyCode.SelectedIndex = ddlCompanyCode.Items.IndexOf(ddlCompanyCode.Items.FindByText(strCompany));
Thanks for everyones help!
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}
I was trying to add a combo box which could get all the product name but unfortunately I follow some tutorials and end up like this.
void fillCombo()
{
try
{
con.Open();
OleDbCommand command = new OleDbCommand("Select * from IblInventory");
command.Connection = con;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
String product = reader.GetString("ProductName"); // << invalid argument
cmbProduct.Items.Add(product);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What could possibly the reason?
From the documentation of OleDbDataReader.GetString you will notice that the argument required by the method is an integer representing the position of the column in the returned record not its name.
If you (rightly) prefer to use the column name then you need to take a detour and use the GetOrdinal method to retrieve the position of the column given the name.
while (reader.Read())
{
int pos = reader.GetOrdinal("ProductName");
String product = reader.GetString(pos);
cmbProduct.Items.Add(product);
}
Another example, practically identical to your situation, can be found in the documentation page on MSDN about OleDbDataReader.GetOrdinal
It is also a common practice to write an extension method that allows you to write code as yours hiding the details of the mapping between name and position. You just need a static class with
public static class ReaderExtensions
{
public string GetString(this OleDbDataReader reader, string colName)
{
string result = "";
if(!string.IsNullOrEmpty(colName))
{
int pos = reader.GetOrdinal(colName);
result = reader.GetString(pos);
}
return result;
}
... other extensions for Int, Decimals, DateTime etc...
}
Now with this class in place and accessible you can call
string product = reader.GetString("ProductName");
it is working in my project
First fill your data in to datatable see the below code
DataTable results = new DataTable();
using(OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select * from IblInventory", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
Now
cmbProduct.DataSource = results ;
cmbProduct.DisplayMember = "ProductName";
cmbProduct.ValueMember = "Id feild of IblInventory table";
I want to shift some variables by one. I searched for the command for it but I couldn't find. If anybody knows it please help me.
Here is the code:
private int shiftNumbers(int number)
{
int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
try
{
con.Open();
cmd = new MySqlCommand(stm, con);
cmd.Parameters.AddWithValue("#number", number);
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
try
{
rdr = cmd.ExecuteReader();
while(rdr.Read()) {
newNumber = rdr.GetInt32(1);
cmd.Parameters.AddWithValue("#newNumber ", (newNumber-1));
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
con.Close();
return 1;
}
I know this code useless but I show it for you to get the logic that I want to do.
I think your approach is wrong.
First, you read from the database, using a select statement;
Then you go over that result, your rdr.Read();
Then you create a new command, updating the original record;
Move forward in your reader (rdr) and repeat from 2 until you are done.
What you are doing now is impossible. You can't get a result set from an update, just a count affected.
Or, if you can, let your update statement do the calculation (it seems it is only subtracting one from the original number, so why not do that in SQL?):
string stm = "UPDATE devices SET number = number - 1 WHERE number>#number";
Yes, your code is really useless. In your update statement you are passing a parameter #newNumber bu not providing it. Closing the connection in catch block.
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
First decide from where you are going to get the #newNumber value and then add that as parameter and use ExecuteNonQuery() method.
If you want pass the other parameter as well in your method and use it like
private int shiftNumbers(int number, int newNumber)
{
//int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
using(SqlConnection con = new SqlConnection(connectionString))
{
cmd = new MySqlCommand(stm, con);
SqlParameter paramNumber = new SqlParameter("#number", SqlDbType.Int);
paramNumber.Value = number;
SqlParameter paramNewNumber = new SqlParameter("#newNumber", SqlDbType.Int);
paramNewNumber.Value = newNumber;
cmd.Parameters.Add(paramNumber);
cmd.Parameters.Add(paramNewNumber);
con.Open();
cmd.ExecuteNonQuery();
}
//Rest of your code logic if any
}
This is my code:
db.Open();
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres, RTRIM(numwave) numwave FROM sorters WHERE kodprod=#kodprod AND sorter_kod=#sorter AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("#numdoc", NumDoc);
command.Parameters.AddWithValue("#kodprod", KodProd.Id);
command.Parameters.AddWithValue("#sorter", SorterKod);
SqlDataReader reader = command.ExecuteReader();
reader.Read();//here error
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
reader.Close();
}
catch (Exception ex)
{ }
Why do I get this error when I run my code?:
Invalid attempt to read when no data is present
You can check whether the DataReader is ready to fetch the rows
if(reader.HasRows)
{
//do the coding here
}
I believe the error will in fact occur on the next line, viz when you access the reader via the index [] operator. What you need to do is check the result of reader.Read() before accessing it:
if (reader.Read())
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
Since you are only returning a maximum of one row (TOP 1) there will either be zero or one rows.
you should do a while loop to check reader contain data. You can also use IF if you are sure the query return only one row. If more than one row you should use While. In your case IF also do the job because you are only taking TOP1
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres,
RTRIM(numwave) numwave FROM sorters WHERE
kodprod=#kodprod AND sorter_kod=#sorter
AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("#numdoc", NumDoc);
command.Parameters.AddWithValue("#kodprod", KodProd.Id);
command.Parameters.AddWithValue("#sorter", SorterKod);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
reader.Close();
}
Use reader.HasRows
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres, RTRIM(numwave) numwave FROM sorters WHERE kodprod=#kodprod AND sorter_kod=#sorter AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("#numdoc", NumDoc);
command.Parameters.AddWithValue("#kodprod", KodProd.Id);
command.Parameters.AddWithValue("#sorter", SorterKod); SqlDataReader
reader = command.ExecuteReader();
if(reader.HasRows)
while(reader.Read())//here error
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
reader.Close();
}
catch{}
EDIT: sorry for the bad formatting, posting code from the Android app is a mess.
EDIT: See Microsoft example here