ASP.Net VB Check if datas exist in database - asp.net

How do I check if data existing in the database or is NULL. I'm getting the following error Object cannot be cast from DBNull to other types . Do I need to add IsDBNULL to the code?
SignedOn.Text = Convert.ToDateTime(reader("SignedOn")).ToShortDateString()

you can check like below
If NOT IsDbNull(reader("SignedOn")) Then
SignedOn.Text = Convert.ToDateTime(reader("SignedOn")).ToShortDateString()
End If
Edit based on comments:
When you know the exact type of the column you can call method relevant to that type like reader.GetDateTime, reader.GetString etc
After conversion if there is a possibility of result can be null then you better check for null before calling ToShortDateString
You can use DateTime.TryParse method if you have store date time in varchar column

Related

PeopleCode reflection for variables

Does PeopleCode have something similar to reflection in C# whereby I can access a variable with the variable name stored in a string? I am aware of the # operator but I think it only applies to fields and records (correct me if I am wrong. I tried and couldn't get it to work.)
Basically, I need to access a Component variable by name with the name itself being variable.
You can do it by # :
Local string &sValue1 = "var1";
getting the value :
winmessage(#(&sValue1));

CLR DateTime object comparison with SQL Server DateTime

I'm using this implementation to conduct server side searching using Entity Framework for jqGrid. The issue that I'm having is that although the search is working fine for text or numerical fields, searching using DateTime values isn't working.
The problem is that the DateTime object in my model class sends the string representation of the object (i.e. in the format 2/9/2014 12:00:00 AM) to the database but the database is formatted as 2014-09-03 00:00:00:000. As a result, the comparison always fails.
I can't change my DateTime property to a string so I'm stumped. The resultset is returned via a stored procedure (a simple SELECT * FROM [TableName]) so I tried formatting the associated Date field and returning that but it returns as an nvarchar.
Has anyone encountered this before or have any recommendations as to how to resolve this issue? I'd appreciate any help, thanks!
Just to provide an answer for anyone who comes across this. I took the following steps to resolve this issue:
1) Made the following change in the JQGrid support class:
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { rule.data }));
to
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { (parseMethod.ReturnType.FullName == "System.DateTime" && rule.data != "") ? Convert.ToDateTime(rule.data, CultureInfo.CreateSpecificCulture("fr-FR")).ToString() : rule.data }));
2a) In my controller, I added the following bit of code whenever I was fetching directly from the table (you have to specify the column names explicitly to truncate the time portion):
//For matching date instead of datetime values
if (wc.Clause.Contains("Date"))
{
wc.Clause = wc.Clause.Replace("DeliveryDate", "DbFunctions.TruncateTime(DeliveryDate)");
}
results = results.Where(wc.Clause, wc.FormatObjects);
2b) If the data was being returned from a stored procedure, I just returned an appropriate Date field from the SP (this approach will work for DateTime fields only if the timestamp portion is all zeros).
Hope this helps someone else.

How can I update a database string value from a TextBox?

I cant update my database through textbox.in the case of numeric value i can update but cant with a string value.
my coding is...
SqlCommand cmdup= new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1",cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
if any one know the ans: reply me
I'd recommend explicitly defining the parameter type to match the type in the DB, and passing the value to Parameters.Add as the appropriate type.
e.g. at the moment, you are passing a string typed value to Parameters.Add, and not defining the type explicitly. Therefore, it will assume the data type from the type of value supplied...so the #prt1 type will be passed in to the DB as NVARCHAR I believe.
If the prt1 field is an INTEGER for example, much safer IMHO to do something like:
cmd.Parameters.Add("#prt", SqlDbType.Int,4).Value = Int32.Parse(TextBox1.Text);
or
cmd.Parameters.AddWithValue("#prt", Int32.Parse(TextBox1.Text));
I always like to fully define the type of the parameters I pass in to SQL to rule out any potential, unexpected issues.
Check the datatype for the #prt1 to see if it is a Int value because you are setting to the same column two different values.
Parse the textBox to Integer as you want to insert a numeric value i.e. Int64.Parse("Textbox1.Text"); well with string it does have problems.
Just a wild guess: Does prt maybe only accept numeric values?

linq to sql "Contains"

if i have a field in my table that i want to verify exists, how do i use the contains method to determine if it exists.
i would have thought the contains method just takes in a string but it seems to take in my whole linq data object
Contains is an extension method for IEnumerable that determines whether a given object is present in the enumerable. That's not what you want here.
I'm guessing that you have a LINQ query like this:
IEnumerable<string> productNames = from p in db.Products select p.ProductName;
And now you want to verify that the ProductName field actually exists to avoid run-time errors. There is actually no need to check that. Try replacing p.ProductName by a field that doesn't exist. The compiler will complain.
Of course, this assumes that the actual database schema matches the one used to generate the database class with MSLinqToSQLGenerator.
Not sure how to do it with LINQ but you could do:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE _NAME ='MyTable' and COLUMN _NAME='MyColumn'
then based on the count returned from the query you will know if the column exists or not.

Cannot insert null where field is Guid (object in SqlDataSource)

I have a table which links to another table in the ASP.NET membership schema.
Problem is, all the PKs for the ASP.NET tables are uniqueidentifier so mine has to be too. When I add a SqlDatasource and call its Insert() method, I get the following error:
Cannot insert the value NULL into column 'DiscountCode', table 'CreamDb.dbo.CustomInfo1'; column does not allow nulls. INSERT fails.
The statement has been terminated.
The uniqueidentifier is also treated as an object (its data type), but there is no Guid data type. I had this problem before, but the schema was much simpler so I could fix it.
How can I go about fixing this? If I get rid of the data type part in the markup (so just leave the field/parameter name but not the data type stuff), I get another error so that is not possible.
Thanks
What do you mean by "there is no Guid data type"? What's wrong with System.Guid? Can't you just use Guid.NewGuid(), set the field appropriately, and do the insert?
EDIT: Just to give a bit more meat: attach an event handler to the Inserting event, and populate the field then, via the DbCommand returned by SqlDataSourceCommandEventArgs.Command. Or change the SQL used by the INSERT command to ask the database to populate the GUID field for you.
A popullar approach when dealing with references to the ASP.NET Membership Provider's data is, instead of keeping a proper foreign key to the GUIDs, instead store something like the LoweredUserName in your table. Then, use the Membership Provider's API to interact with the object you need. In some cases, you need an ObjectDataSource abstraction layer to accomplish CRUD scenarios.
Set the default value of the column in SQL Sever to "newid()".
Asp.net won't send the value, and the field will get a new guid.

Resources