I am having a strange message displayed on the asp:label when trying to display data from a database. During page_load the asp:label is meant to be populated from a datasource however is displays the following message/text "System.Data.SqlClient.SqlDataReader"
What could be causing this?
I have written a small method in the page load of the .aspx.cs page.
labelName is the one which is displaying this message:
public partial class edit_questionnaire : System.Web.UI.Page
{
OsqarSQL GetData;
protected void Page_Load(object sender, EventArgs e)
{
string questionnaireId = Session["qID"].ToString();
int qid = Convert.ToInt32(questionnaireId);
GetData = new OsqarSQL();
string name = GetData.GetQuestionnaireName(qid);
labelName.Text = name;
}
}
Which calls the following method:
public string GetQuestionnaireName(int questionnaireId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetQuestionnaireName", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("#QUEST_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = questionnaireId;
SqlDataReader qName = getData(myCommand);
while (qName.Read())
{
returnValue = qName.ToString();
}
_productConn.Close();
return returnValue;
}
And uses this stored procedure:
ALTER PROCEDURE [hgomez].[GetQuestionnaireName]
(
#QUEST_ID int
)
AS
/*SET NOCOUNT ON;*/
SELECT QuestionnaireName FROM [Questionnaires] WHERE QuestionnaireID = #QUEST_ID
RETURN
public string GetQuestionnaireName(int questionnaireId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetQuestionnaireName", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("#QUEST_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = questionnaireId;
SqlDataReader qName = getData(myCommand);
while (qName.Read())
{
returnValue = qName[0].ToString();
}
_productConn.Close();
return returnValue;
}
You were assigning the SqlDataReader to your returnValue rather than reading the value.
You need to use the GetValue method of SqlDataReader
SqlDataReader qName = getData(myCommand);
while (qName.Read())
{
returnValue = qName.GetValue(0).ToString();
}
The problem is in the line below - it is a data reader, not a string returned by the data reader:
returnValue = qName.ToString();
You should replace this with
returnValue = qName.GetString(0);
What you are getting is SqlDataReader type as string. To read a string out of SqlDataReader you will have to use GetString method. And as parameter you should pass the index of field. As you have only one field which you are trying to read pass zero here.
You should return value like this
returnValue = qName.GetString(0);
Alternatively you can do
returnValue = qName.GetString("QuestionnaireName");
//this is better to name fields
Or you can simply write
returnValue = qName[0].ToString();
That's because you are calling SqlDataReader.ToString(). That will return the string of the type, which is in fact "System.Data.SqlClient.SqlDataReader".
Use returnValue = qName.GetString(0);
You are converting qName.ToString(), you can try qName[0].ToString(); with [0] being the index of select column inside your stored procedure.
Related
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 have an issue. please help to solve my problem
I have a SQL function
function [dbo].[fnKudishikaAmt]
(#ParishName nvarchar(100), #Hno int, #dateto datetime = Null)
Returns Decimal(15,2)
This function shows proper result by using the execute command
Select dbo.fnKudishikaAmt('St.George Malankara Catholic Church', 29, default)
My requirement is this function should be called from C#
I am getting the error
Conversion failed when converting datetime from character string
Code:
public double kudishikatotal(string ParishName, Int32 HouseNo)
{
String SQLText = "select ChurchDB.dbo.fnKudishikaAmt(#ParishName, #Hno, #dateto) as fnresult";
SqlCommand cmd = new SqlCommand(SQLText);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ParishName", ParishName);
cmd.Parameters.AddWithValue("#Hno", HouseNo);
cmd.Parameters.AddWithValue("#dateto", "default");
string rval = GetSingleValue(cmd);
double kudiamt = 0;
if (rval != null)
{
kudiamt = Convert.ToDouble(rval);
}
return kudiamt;
}
private static string GetSingleValue(SqlCommand cmd)
{
string ConString = connectionstring();
string returnvalue = "";
using (SqlConnection con = new SqlConnection(ConString))
{
cmd.Connection = con;
con.Open();
returnvalue = cmd.ExecuteScalar().ToString();
con.Close();
}
return returnvalue;
}
If you've declared default value for parameter in stored procedure - then you can just not pass this parameter from c# code at all, and in this case it will have default value.
In your case exception thrown because it's impossible to convert string "default" to SqlDateTime which is your parameter type.
YOu can use if condition while sending the datetime parameter.
if(some condition)
{
cmd.Parameters.AddWithValue("#dateto", dateTimeValue);
}
Here datetimeValue is the value you want to pass. So you will be passing dateTimeValue only if required.
The error is due to the string "default" you passed.
I try to receive a nickname from an user from the database, but it always returns the value which is assigned to the string nickname variable.
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
nickname = Convert.ToString(command.ExecuteReader());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
}
This is my code in the form:
private void listBoxBerichten_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
Blog blog = (Blog)lb.Items[lb.SelectedIndex];
int blogid = blog.BlogID;
geselecteerdeBlog = dk.GetGeselecteerdeBlog(blogid);
string blogeigenaar;
foreach (Blog b in geselecteerdeBlog)
{
blogeigenaar = dk.GetEigenaarBlog(b.GebruikerID); //This is the method where is the problem
tbGeblogd.Text = Convert.ToString(b.Datum);
tbTitel.Text = b.Titel;
tbDoor.Text = blogeigenaar;
tbBlogInhoud.Text = b.Inhoud;
}
}
The parameter works, it reads that parameter from the form.
When I change string nickname = null to string nickname = 'hello' then it returns nickname as hello. So it returns the assigned value. When I keep string nickname = null then it returns null
What am I doing wrong? the SQL-query is right, and the user exist in the database. I'm not getting any errors or warnings.
Thanks!
Your code needs to be changed in this way
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
OracleDataReader reader = command.ExecuteReader();
// Now try to read from the reader (and position the reader on the first record returned)
if(reader.Read())
nickname = reader[0].ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
The ExecuteReader method returns an OracleDataReader and this object needs to be positioned on the first record before trying to read from it. Thus you need to call the Read method, and if that method returns true you could read the string.
Said that however, when you have a query that returns just one row and one column then a very fast approach is through the ExecuteScalar method
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
// ExecuteScalar returns the value of the first row/first column, or null if
// there is no record to return. Need to be carefull here
object result = command.ExecuteScalar();
if(result != null)
nickname = result.ToString();
As a side note, I can't see the full code, but it seems that you keep a global connection object.
This is considered a bad and needless practice because the Connection Pooling mechanism could do a better work to keep the connection objects ready to use
You cannot access a datareader this way. You will have to loop through the datareader and get the data. See http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader.aspx for more info.
Instead of
nickname = Convert.ToString(command.ExecuteReader());
try this
OracleDataReader reader = command.ExecuteReader();
nickname = "";
while (reader.Read())
{
nickname = Convert.ToString(reader[0]));
}
when you select items from the listbox, you want to delete selecteditems. Why doesnt it work when selected data removed from database? I must have missed something. I got error message
No mapping exists from object type.
This is a method parameter:
IsDelete = _dinnerRemover.RemoveDinners(lstDinner.SelectedItems);
This class is to delete data from database
public bool RemoveDinners(dynamic dinnerItems)
{
Dinners = new List<FoodInformation>();
using (var sqlConn = new SqlConnection(_sqlConnectionString))
{
const string sqlQuery = "delete from DinnerTemplates where Dinner = #dinner";
using (var command = new SqlCommand(sqlQuery, sqlConn))
{
try
{
//command.CommandType = CommandType.StoredProcedure;
//command.CommandText = "sp_dinner";
foreach (var item in dinnerItems)
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#dinner", item);
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlConn.Close();
}
}
}
return Dinners;
}
If dinnerItems is a list of strings then say that, don't use dynamic unless you absolutely have to.
To delete a bunch of items, issue one sql query with an IN clause. Don't issue lots of individual queries.
Try this:
public int RemoveDinners(List<string> dinnerItems)
{
using (var sqlConn = new SqlConnection(_sqlConnectionString))
{
const string sqlQuery = "delete from DinnerTemplates where Dinner in ({0})";
using (var command = new SqlCommand())
{
var paramNames = new string[dinnerItems.Count];
int i = 0;
foreach (string item in dinnerItems)
{
string paramName = "#Dinner" + i;
command.Parameters.AddWithValue(paramName, item);
paramNames[i] = paramName;
i += 1;
}
command.CommandText = String.Format(sqlQuery, String.Join(",", paramNames));
command.Connection = sqlConn;
command.CommandType = CommandType.Text;
sqlConn.Open();
return command.ExecuteNonQuery();
}
}
}
You have to bear in mind that you kind of left out some really relevant code, like what is a DinnerItem, since you're getting the error on a line related to its type.
However, the reason you're getting that error is because item can't be marshaled to a type of something like string or int.
That's probably because item is likely a custom class. One option would be to override the ToString method of the class:
public override string ToString() {
// return some property value, or set of property values
// strung together here.
}
another option would be to send in the actual Property you want off of item when issuing AddWithValue.
You need to define SqlDbType for command's parameter.
don't use dynamic type,use string..
if i were you,i would rather
IsDelete = _dinnerRemover.RemoveDinners(lstDinner.SelectedItems.ToString());
change the parameter to :
public bool RemoveDinners(string dinnerItems)
and the query to :
const string sqlQuery = "delete from DinnerTemplates where Dinner = dinnerItems";
I have used the store procedure in MS-Sql for inserting for particular page it is working fine but I also need the same store procedure for other page it is finding me the error.
protected void btnsubmitt_Click(object sender, EventArgs e)
{
ArrayList arParameters = ReturnParameter();
DataSet dsInsertProfile = objadmin.GetGridData(arParameters, objconstant.sSP_INSERT_PROFILE);
if (int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString()) == 0)
{
pnlProfile.Visible = false;
pnlThank.Visible = true;
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter()
{
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
ArrayList arSample = new ArrayList();
Object[] c_email_id = new Object[3] { "#strEmailID", "varchar", email};
arSample.Add(c_email_id);
return arSample;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
Mystore procedure
ALTER Procedure [dbo].[spInsert_profile]
( #strEmailID varchar(200)
)
AS
BEGIN
DECLARE #intEmail INT
SET #intEmail = (SELECT COUNT(*) FROM gdt_Users WHERE [c_email_id]=#strEmailID)
IF #intEmail = 0
BEGIN
Insert into gdt_Users([c_email_id],[d_modified_dttm],[d_created_dttm])values(#strEmailID,GETDATE(),GETDATE())
SELECT #intEmail
END
ELSE
BEGIN
SELECT #intEmail
END
END
Here, I was facing a problem. It was throwing an exception
ERROR: Failed to convert parameter value from string to Int64
So, I've add this code
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
in arraylist returnparameter() method. Then, it threw that exception
ERROR: Input string was not in correct format
How can I solve this? Can you help me?
In your code I can find Convert.ToInt64 only at one place which is
Int64 email = Convert.ToInt64(txtemail.Text.ToString());
You would not be passing valid number to Convert.ToInt64( as txtemail will have string not a number. You should give a number in txtemail or use the correct textbox for converting the string to int64.
Keep in mind Convert.ToInt64( converts string to number only if the
string is number.
Your stored procedure expects varchar(200) which is equivalent to String of length 200, so email should be string and not number. E.g. yourname#someemail.com is a string. Am just curious, what makes you think is int64. It should be
string email = txtemail.Text;
Your code down here indicates email should be string by using "varchar"
string email = txtemail.Text; //change your code to this
ArrayList arSample = new ArrayList();
Object[] c_email_id = new Object[3] { "#strEmailID", "varchar", email};