Can't convert DateTime to string in C# - c#

Hi i'm trying to make a reservation page. If someone makes a reservation that date gets saved in the database and will also be showed on their page. The type of the column 'dayid' is date in postgresql. In razor pages C# i used the type DateTime for variable Dayid. I need to convert the dayid value from database to a string. But i don't know how to solve this error:
"No overload for method 'ToString' takes 1 arguments"
Here is the code
public List<ReservationModel> ShowReservation()
{
var cs = Database.Database.Connector();
List<ReservationModel> res = new List<ReservationModel>();
using var con = new NpgsqlConnection(cs);
{
string query = "Select dayid, locationid FROM reservation";
using NpgsqlCommand cmd = new NpgsqlCommand(query, con);
{
cmd.Connection = con;
con.Open();
using (NpgsqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
res.Add(new ReservationModel { Dayid = dr["dayid"].ToString("MM/dd/yyyy"), Locationid = dr["locationid"].ToString() });
}
}
con.Close();
}
}
return res;
}

The compile-time type of the NpgsqlDataReader indexer is just object, and the object.ToString() method is parameterless. You need an expression of type DateTime to call the ToString overload that you want.
You could cast to DateTime instead:
while (dr.Read())
{
res.Add(new ReservationModel
{
Dayid = ((DateTime) dr["dayid"]).ToString("MM/dd/yyyy"),
Locationid = dr["locationid"].ToString()
});
}
(Or find the column index and call dr.GetDateTime(...).)
However, I'd encourage you to change your model (ReservationModel) to keep the value as a DateTime instead of converting it to a string at this point anyway. In general, it's a good idea to keep data in its most natural data type for as much of the time as possible, only converting it to/from text at boundaries.

Related

'Invalid attempt to read when no data is present' error

I've got this code block:
using (SqlConnection con2 = new SqlConnection(str2))
{
using (SqlCommand cmd2 = new SqlCommand(#"SELECT * FROM VW_MOS_DPL_AccountValidation WHERE CUST_NUM = #CNum", con2))
{
con2.Open();
cmd2.Parameters.AddWithValue("#CNum", TBAccountNum.Text);
using (SqlDataReader DT2 = cmd2.ExecuteReader())
{
// If the SQL returns any records, process the info
if (DT2.HasRows)
{
// If there's a BusinessID (aka Business Type), fill it in
string BizID = (DT2["Business_ID"].ToString());
if (!string.IsNullOrEmpty(BizID))
{
DDLBustype.SelectedValue = BizID;
}
}
}
con2.Close();
}
}
When it gets to the line
string BizID = (DT2["Business_ID"].ToString());
it throws an error:
Invalid attempt to read when no data is present.
Why would it get past if (DT2.HasRows) if there was no data?
You need to call
if(DT2.Read())
....
before proceding to read data from a DataReader.
The HasRows tells you only that the SqlDataReader contains data, but the SqlDataReader loads one record at time from the connection. Thus every tentative to extract the data from the SqlDataReader should be preceded by a call to Read to position the SqlDataReader on the first record returned through the connection.
And, because the Read method returns true if the call has been able to read a record, you could replace the call to HasRows with something like this
using (SqlDataReader DT2 = cmd2.ExecuteReader())
{
// If the SQL returns any records, process the info
while(DT2.Read())
{
// If there's a BusinessID (aka Business Type), fill it in
string BizID = (DT2["Business_ID"].ToString());
if (!string.IsNullOrEmpty(BizID))
{
DDLBustype.SelectedValue = BizID;
}
}
}
By the way, if it is possible to have a NULL for BusinessID then you need a different test to avoid exception problems
int bizColIndex = DT2.GetOrdinal("Business_ID");
string BizID = (DT2.IsDBNull(bizColIndex) ? string.Empty : DT2.GetString(bizColIndex));
if (!string.IsNullOrEmpty(BizID))
{
DDLBustype.SelectedValue = BizID;
}

Storing SQL Select result into String Variable

I am trying to store the result from my SQL query into a string variable. This is what I have:
string strName = dt.Rows[i][name].ToString();
string selectBrandID = "SELECT [Brand_ID] FROM [myTable] WHERE [real_name] = '" + strName + "'";
using (SqlCommand sqlCmdSelectBrandID = new SqlCommand(selectBrandID, sqlConn))
{
sqlCmdSelectBrandID .Connection.Open();
using (SqlDataReader reader = sqlCmdSelectBrandID.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string newBrandID = reader.GetString(reader.GetOrdinal("Brand_ID"));
}
sqlCmdSelectBrandID.Connection.Close();
}
}
This currently throws the exception Unable to cast object of type 'System.Int32' to type 'System.String'. On string newBrandID =reader.GetString(reader.GetOrdinal("Brand_ID")); line.
Any advice on how to fix this?
If your Brand_ID is stored in an integer field, then you should keep it as an integer. The GetString fails because the underlying field is not a string, you could simply use the GetInt32 (see the SqlDataReader docs)
int newBrandID = reader.GetInt32(reader.GetOrdinal("Brand_ID"));
Then, if for whatever purpose you want it as a string, it is just a matter to apply the ToString() method to your integer
string brandID = newBrandID.ToString();

Linq "Unable to cast object of type 'System.DateTime' to type 'System.String'" error

I am using linq to extract some information from database.
Sql script:
TYPE CURS IS REF CURSOR;
CREATE OR REPLACE
PROCEDURE PROCEDURE_NAME (
Cursor1 OUT CURS)
AS
BEGIN
OPEN Cursor1 FOR
SELECT NO, TITLE, TO_CHAR(STARTDATE) STARTDATE
FROM TABLE_1;
END;
Linq code:
var query = from e in getItem().AsEnumerable()
select new {
No = e.Field<string>("NO"),
Title = e.Field<string>("TITLE"),
StartDate = e.Field<string>("STARTDATE")
};
return query.Select(e => new ClassA()
{
No = e.No,
Title = e.Title,
StartDate = e.StartDate
}).ToList<ClassA>();
Class A:
public class ClassA {
public string No { get; set; }
public string Title { get; set; }
public string StartDate { get; set; }
}
getItem():
public DataTable getItem() {
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "PROCEDURE_NAME";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("Cursor1", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
da.Fill(ds);
return ds.Tables[0];
}
But the query always return me error Unable to cast object of type 'System.DateTime' to type 'System.String'. but i already check that the STARTDATE is extracted as System.String. How to solve this? Its killing me..
[UPDATE]
It works now, I change all the data type of STARTDATE to DateTime and extract it from database without conversion.
But still, I do not understand why the error will appear.
To have a formal answer to this question, I will post here the answer of the owner. (I will delete this if the owner will include his answer here).
[UPDATE]
It works now, I change all the data type of STARTDATE to DateTime and extract it from database without conversion.
In the stored procedure, remove the function TO_CHAR. This function will convert datetime columns to varchar2 columns.
TYPE CURS IS REF CURSOR;
CREATE OR REPLACE
PROCEDURE PROCEDURE_NAME (
Cursor1 OUT CURS)
AS
BEGIN
OPEN Cursor1 FOR
SELECT NO, TITLE, STARTDATE
FROM TABLE_1;
END;

How to make Sqlcommand accept null values

I'm trying to get data in a gridview from a database to show up in text boxes upon clicking and it works fine for the rows with no null data, although since my int columns have some null values my GetInt32 methods keep returning "Data is Null. This method or property cannot be called on Null values."
Is there a simple way to fix or work around this? Do I replace GetInt32 with another method? I'd like for the data that is null to show up blank/empty in the text boxes if possible. Here's my code if you have any suggestions, thanks.
public ArrayList GetAllPersonnel(int WorkerID) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
String query = "Select * FROM Personnel WHERE WorkerID = " + WorkerID;
using (var command = new SqlCommand(query, connection)) {
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read()) {
String firstname = reader.GetString(1);
String lastname = reader.GetString(2);
String occupation = reader.GetString(3);
String deployment = reader.GetString(4);
int disasterid = reader.GetInt32(5);
String location = reader.GetString(6);
int deployedhours = reader.GetInt32(7);
int resthours = reader.GetInt32(8);
list.Add(firstname);
list.Add(lastname);
list.Add(occupation);
list.Add(deployment);
list.Add(disasterid);
list.Add(location);
list.Add(deployedhours);
list.Add(resthours);
}
connection.Close();
reader.Close();
return list;
}
}
}
You should use IsDBNull method of the SqlDataReader
int resthours = (!reader.IsDBNull(8) ? reader.GetInt32(8) : 0);
or, more directly
list.Add((!reader.IsDBNull(8) ? reader.GetInt32(8).ToString(): string.Empty));
Said that, I have noticed that you use a string concatenation to build the sql command text to retrieve records. Please do not do that. It is very dangerous and could lead to Sql Injection
String query = "Select * FROM Personnel WHERE WorkerID = #wkID";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#wkID", WorkerID);
var reader = command.ExecuteReader();
....
OK, so you're effectively saying that everything you display should be a string type, which is fine, I'm just making that point because you stated you want even integers to show up as an empty string. So how about this code?
String firstname = reader.GetString(1);
String lastname = reader.GetString(2);
String occupation = reader.GetString(3);
String deployment = reader.GetString(4);
String disasterid = reader.IsDBNull(5) ? string.Empty : reader.GetString(5);
String location = reader.GetString(6);
String deployedhours = reader.IsDBNull(7) ? string.Empty : reader.GetString(7);
String resthours = reader.IsDBNull(8) ? string.Empty : reader.GetString(8);
list.Add(firstname);
list.Add(lastname);
list.Add(occupation);
list.Add(deployment);
list.Add(disasterid);
list.Add(location);
list.Add(deployedhours);
list.Add(resthours);
Now, the reason I stated that you want to leverage everything as a string is because the default value for a int is 0 and that wouldn't meet the empty text box requirement.
You have at least two ways to sort this out
Modify your sql to select either zero or whatever you think suitable in the place of null value. This will ensure that you always have an integer value in the integer column. It can be done in the following manner
select ISNULL ( ColumnName , 0 ) as ColumnName from xxx
Always fetch object from the reader and check if it is null or not. If it is null then replace it with suitable value.

c# and stored procedures, unique code per SProc?

I'm writing an application which first connect to the database and retrieves a dt containing a list of all the stored procedures, inputs and their associated datatypes. The user then selected a SProc from the combobox and has to enter in the necessary inputs. The app will then connect to the database and run the selected SProc with the user specified inputs and return the results in a datatable.
What I'm unsure about is if I need to write a specific method for each SProc. I'm assuming so since I don't see how I could state what the parameters are otherwise.
Apologies for not making this clear the first time. Let me know if this still isn't clear enough.
Example is shown below (this is someone else's code)
public static GetDaysDTO GetDays(int offset)
{
GetDaysDTO ret = new GetDaysDTO { TODAY = DateTime.Now, TOMORROW = new DateTime(2012, 01, 01) };
SqlConnection con = new System.Data.SqlClient.SqlConnection(#"Server = FrazMan-pc\Programming; Database = master; Trusted_Connection = True");
SqlCommand cmd = new System.Data.SqlClient.SqlCommand
{
CommandText = "GetDays",
CommandType = System.Data.CommandType.StoredProcedure,
CommandTimeout = 1,
Connection = con,
Parameters = { new System.Data.SqlClient.SqlParameter("#offset", System.Data.SqlDbType.Int) { Value = offset } }
};
using (con)
{
con.Open();
using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ret.TODAY = DateTime.Parse(reader[0].ToString());
ret.TOMORROW = DateTime.Parse(reader["TOMORROW"].ToString());
}
}
}
return ret;
}
What you're looking for is a design pattern called Factory and a way to tell which typed data table to create on each SP call
If you have the list of the parameters for each procedure, u could instantiate the Parameters object via a loop:
This class will be used to fill the params of the sp received from the db
class ParamData
{
public object Data;
public SqlDbType type;
public string ParamName;
}
and then later on, when calling the sp, u should also pass thie ParamData object to the method, and used it to fill the params of ur sp dynamicly in a loop:
List<ParamData> list = new List<ParamData>();
//initialize command here as u did
SqlCommand cmd;
foreach (ParamData param in list)
{
SqlParameter sqlParam = new SqlParameter(param.ParamName, param.type);
sqlParam.Value = param.Data;
cmd.Parameters.Add(sqlParam);
}
//execute the command
//fill the datatable with result
DataTable dt = GetTableBySPName("GetDays");
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
The only thing you need to add is the mapping between ur typed datatables and the returned table by the procedure.
You can add a method to do this:
private DataTable GetTableBySPName(string name)
{
DataTable dt = null;
switch (name)
{
case "GetDays":
{
dt = new GetDatsDTO();
break;
}
}
return dt;
}

Categories