Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Saturday, March 31, 2012

Strange behavior with activate user in windows 2003 server

Hi,

I code an activate user process who works very great on my computer but when i put it on my server (win server 2003 / SQL server 2005) it doesn't validate (isapproved=true) the user.

Activate.aspx.vb :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim UserNameEmail As String = Request.QueryString("useremail")
Dim Username As String = Membership.GetUserNameByEmail(UserNameEmail)

If Not String.IsNullOrEmpty(UserNameEmail) Then
Dim usr As MembershipUser = Membership.GetUser(Username)
If Not Nothing Is usr Then
usr.IsApproved = True
Membership.UpdateUser(usr)
Response.Redirect("activate_success.aspx")
Else
Response.Redirect("activate_error.aspx")
End If
Else
Response.Redirect("activate_error.aspx")
End If
Else
Response.Redirect("activate_error.aspx")
End If
End Sub


I don't know why? Someone have an idea please?

Hi,

I need to mention that if i use the UserID for the activation it works:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim UserName As String = Request.Params("USERID")
Dim providerUserKey As Guid = New Guid(UserName)

If Not String.IsNullOrEmpty(UserName) Then
Dim usr As MembershipUser = Membership.GetUser(providerUserKey)
If Not Nothing Is usr Then
usr.IsApproved = True
Membership.UpdateUser(usr)
Response.Redirect("activate_success.aspx")
Else
Response.Redirect("activate_error.aspx")
End If
Else
Response.Redirect("activate_error.aspx")
End If
Else
Response.Redirect("activate_error.aspx")
End If
End Sub

But i want to activate the user with passing only his email and not his UserID because USerID is too confidential...


Ok i understand why it is not working...

Many users can have the same email so the database doesn't know which user to pick...

I will think of that...

Wednesday, March 28, 2012

Strange Characters in Asp.Net Text Box

Hello,

I have a form which saves some data to an SQL 2005 database
If the text written in the text box contains characters such as "??áàéí" when I load the data again I get a few strange characters: "?§?£??? ???"

What is going wrong here?

How can I solve this?

Thanks,
Miguel

What encoding did you set for the pages? Set the responseEncoding to "utf-8"

Check this link on how to set it in the web.config filehttp://msdn2.microsoft.com/en-us/library/hy4kkhe0(vs.80).aspx

Thanks

Strange Characters in Asp.Net Text Box

Hello,
I have a form which saves some data to an SQL 2005 database
If the text written in the text box contains characters such as
"=E7=E3=E1=E0=E9=ED" when I load the data again I get a few strange charact=
ers:
"=C3=A7=C3=A3=C3=A1=C3 =C3=A9=C3"
What is going wrong here?
How can I solve this?
Thanks,
MiguelHello shapper,
This seems like a flaw in Unicode encoding mode in your URL If the character
s
you have types are unicode, then make sure that you save the file in proper
Unicode mode. If you are using VS2005, then you will find a command 'Advance
d
Save Options' which does this.
Thanks
Cyril Gupta
-- You can do anything with a little bit of 'magination.
-- I've been programming so long, my brain is now software.

> Hello,
> I have a form which saves some data to an SQL 2005 database
> If the text written in the text box contains characters such as
> "" when I load the data again I get a few strange characters:
> "??á é"
> What is going wrong here?
> How can I solve this?
> Thanks,
> Miguel

Strange Characters in Asp.Net Text Box

Hello,

I have a form which saves some data to an SQL 2005 database
If the text written in the text box contains characters such as
"" when I load the data again I get a few strange characters:
"??á é"

What is going wrong here?

How can I solve this?

Thanks,
MiguelHello shapper,

This seems like a flaw in Unicode encoding mode in your URL If the characters
you have types are unicode, then make sure that you save the file in proper
Unicode mode. If you are using VS2005, then you will find a command 'Advanced
Save Options' which does this.

Thanks
Cyril Gupta

-- You can do anything with a little bit of 'magination.

-- I've been programming so long, my brain is now software.

Quote:

Originally Posted by

Hello,
>
I have a form which saves some data to an SQL 2005 database
If the text written in the text box contains characters such as
"" when I load the data again I get a few strange characters:
"??á é"
What is going wrong here?
>
How can I solve this?
>
Thanks,
Miguel

Monday, March 26, 2012

Strange Date Problem

Hi all,

i am using visual studio 2005 and sql server 2005, i am developing a web application using visual basic 2005. i also let you know that i am in UK.

i am having a strange problem. i have got a form from whcih i need to insert the date values into the data base my querystring is as follows.

StrSql = "insert into tasks (TaskName,Sdate,PropEdate,InitID,TaskManager) values (" & _
"'" & Me.TxtTaskName.Text & "'," & _
"'" & Me.TxtSDate.Text & "'," & _
"'" & Me.TxtEdate.Text & "'," & _
Session("InitID") & "," & _
Me.DropDownList1.SelectedValue & _
")"

which is working fine except that it is storing date in different format that is mm/dd/yyyy.

on my other form i again want to insert the date value wich is not working.
my querystring is

StrSql = "insert into tasklog (taskid,currentstatus,updatedon,comments) values (" & _
Me.GridView1.SelectedValue & "," & _
Me.TxtRecentpos.Text & "," & _
"'" & Me.TxtDate.Text & "'," & _
"'" & Me.TxtComments.Text & "'" & _
")"

when i try to run this query it gives me the following error message:

The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value..

i have checked in the sqlserver and both the tables have got the smalldatetime datatype for my fields. it's really scaring for me that it is working on one place and not working on other.
any help would be highly appretiated.
thanksNo matter what the settings are in your code/computer/database, when putting date values into SQL statements, you cannot use the UK format (dd/mm/yyyy).

You must use either the US format (mm/dd/yyyy), or better a format which cannot be mis-interpreted (like yyyy/mm/dd).

If you format the values in this style, you will probably find that the code works perfectly.
Hi si,

i have tried both us format and the other format you told me. but sitll giving the same erroe message.

regards
Faizee
You must use either the US format (mm/dd/yyyy), or better a format which cannot be mis-interpreted (like yyyy/mm/dd).

If you format the values in this style, you will probably find that the code works perfectly.[/QUOTE]

Hi Si sorry i have tried (mm-dd-yyyy) and (yyyy-mm-dd) both are working fine. is it not possible that user enter the date in UK format ( i am using vb 2005) and then i format this to us format or other format to save in the SQL Server so that the users are not confused?

regards
Of course... you just have to convert it before using it in an SQL string.

I haven't used .Net enough to suggest the code you would use to convert it, but can recommend that you use a special date control rather than a textbox - as this is always clear to the user, and to your code too (no matter what settings the PC has).
The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value..

This can be caused by trying to put a date less than 1/1/1900 or larger than 6/6/2079

Also check out using parameters with your SQL strings, it prevents sql injection as well has handles special characters.
Thanks Si and Bill,

i am using RJS Calendar control now and it's working fine.

thanks a lot for your help

Faizee

Strange DBNULL Error - Please Help!

Dear Group

I'm having a very weird problem. Any hints are greatly appreciated.

I'm returning two values from a MS SQL Server 2000 stored procedure to my
Webapplication and store them in sessions.
Like This:

prm4 = cmd1.CreateParameter
With prm4
..ParameterName = "@dotnet.itags.org.Sec_ProgUser_Gen"
..SqlDbType = SqlDbType.VarChar
..Size = 10
..Direction = ParameterDirection.Output
End With

prm5 = cmd1.CreateParameter
With prm5
..ParameterName = "@dotnet.itags.org.Sec_ProgUser_Key"
..SqlDbType = SqlDbType.VarChar
..Size = 10
..Direction = ParameterDirection.Output
End With
...
cmd1.ExecuteNonQuery()
...
Session("Sec_ProgUser_Gen") = prm4.Value
Session("Sec_ProgUser_Key") = prm5.Value

Both output parameters are declared as varchar(10) within the stored
procedure. If I run the stored procedure in SQL Analyzer, I'm getting a
string value for each of them. E.g. @dotnet.itags.org.Sec_ProgUser_Gen is "1110011",
@dotnet.itags.org.Sec_ProgUser_Key = "1100".

Now the strange thing happens if I try to run the following code:

Sub MyTest()
Dim MyString1 As String
Dim MyString2 As String
MyString1 = CStr(Session("Sec_ProgClient_Key"))
...
MyString2 = CStr(Session("Sec_ProgUser_Gen"))
End Sub

It fails in line 'MyString2 = CStr(Session("Sec_ProgUser_Gen"))' with Cast
from type 'DBNull' to type 'String' is not valid.

I don't understand this. They are both the same, the only difference is the
length of the string. Help!

Additional Information:
The values for @dotnet.itags.org.Sec_ProgUser_XXX are created in the stored procedure with a
statement like this:
SET @dotnet.itags.org.Sec_ProgUser_Key = (SELECT Convert(varchar(1),Key_CanCreateKey) +
Convert(varchar(1),Key_CanCreateTransaction) +
Convert(varchar(1),Key_CanView) + Convert(varchar(1),Key_CanDelete) FROM
i2b_proguser_securityprofile WHERE SecurityProfileID = @dotnet.itags.org.SecurityProfileID)

The datatype of the source columns used to be bit then changed them to
Integer as I thought this might cause the problem. (Although it shouldn't as
the values get converted to varchar without a problem in the stored
procedure. No fields contain NULL values, only 1 or 0.Did you figure this out?

--
Regards,
Alvin Bruney [ASP.NET MVP]
Got tidbits? Get it here...
http://tinyurl.com/3he3b
"Martin" <theintrepidfox@.hotmail.com> wrote in message
news:7217238c.0401221018.3b36790a@.posting.google.c om...
> Dear Group
> I'm having a very weird problem. Any hints are greatly appreciated.
> I'm returning two values from a MS SQL Server 2000 stored procedure to my
> Webapplication and store them in sessions.
> Like This:
> prm4 = cmd1.CreateParameter
> With prm4
> .ParameterName = "@.Sec_ProgUser_Gen"
> .SqlDbType = SqlDbType.VarChar
> .Size = 10
> .Direction = ParameterDirection.Output
> End With
> prm5 = cmd1.CreateParameter
> With prm5
> .ParameterName = "@.Sec_ProgUser_Key"
> .SqlDbType = SqlDbType.VarChar
> .Size = 10
> .Direction = ParameterDirection.Output
> End With
> ...
> cmd1.ExecuteNonQuery()
> ...
> Session("Sec_ProgUser_Gen") = prm4.Value
> Session("Sec_ProgUser_Key") = prm5.Value
> Both output parameters are declared as varchar(10) within the stored
> procedure. If I run the stored procedure in SQL Analyzer, I'm getting a
> string value for each of them. E.g. @.Sec_ProgUser_Gen is "1110011",
> @.Sec_ProgUser_Key = "1100".
> Now the strange thing happens if I try to run the following code:
> Sub MyTest()
> Dim MyString1 As String
> Dim MyString2 As String
> MyString1 = CStr(Session("Sec_ProgClient_Key"))
> ...
> MyString2 = CStr(Session("Sec_ProgUser_Gen"))
> End Sub
> It fails in line 'MyString2 = CStr(Session("Sec_ProgUser_Gen"))' with Cast
> from type 'DBNull' to type 'String' is not valid.
> I don't understand this. They are both the same, the only difference is
the
> length of the string. Help!
> Additional Information:
> The values for @.Sec_ProgUser_XXX are created in the stored procedure with
a
> statement like this:
> SET @.Sec_ProgUser_Key = (SELECT Convert(varchar(1),Key_CanCreateKey) +
> Convert(varchar(1),Key_CanCreateTransaction) +
> Convert(varchar(1),Key_CanView) + Convert(varchar(1),Key_CanDelete) FROM
> i2b_proguser_securityprofile WHERE SecurityProfileID = @.SecurityProfileID)
> The datatype of the source columns used to be bit then changed them to
> Integer as I thought this might cause the problem. (Although it shouldn't
as
> the values get converted to varchar without a problem in the stored
> procedure. No fields contain NULL values, only 1 or 0.
Hi Alvin

Yes. Thanks for asking. Forgot OUTPUT for @.Sec_ProgUser_Gen

"Alvin Bruney" <vapor at steaming post office> wrote in message news:<OFZOOxs4DHA.1504@.TK2MSFTNGP12.phx.gbl>...
> Did you figure this out?
> --
> Regards,
> Alvin Bruney [ASP.NET MVP]
> Got tidbits? Get it here...
> http://tinyurl.com/3he3b
> "Martin" <theintrepidfox@.hotmail.com> wrote in message
> news:7217238c.0401221018.3b36790a@.posting.google.c om...
> > Dear Group
> > I'm having a very weird problem. Any hints are greatly appreciated.
> > I'm returning two values from a MS SQL Server 2000 stored procedure to my
> > Webapplication and store them in sessions.
> > Like This:
> > prm4 = cmd1.CreateParameter
> > With prm4
> > .ParameterName = "@.Sec_ProgUser_Gen"
> > .SqlDbType = SqlDbType.VarChar
> > .Size = 10
> > .Direction = ParameterDirection.Output
> > End With
> > prm5 = cmd1.CreateParameter
> > With prm5
> > .ParameterName = "@.Sec_ProgUser_Key"
> > .SqlDbType = SqlDbType.VarChar
> > .Size = 10
> > .Direction = ParameterDirection.Output
> > End With
> > ...
> > cmd1.ExecuteNonQuery()
> > ...
> > Session("Sec_ProgUser_Gen") = prm4.Value
> > Session("Sec_ProgUser_Key") = prm5.Value
> > Both output parameters are declared as varchar(10) within the stored
> > procedure. If I run the stored procedure in SQL Analyzer, I'm getting a
> > string value for each of them. E.g. @.Sec_ProgUser_Gen is "1110011",
> > @.Sec_ProgUser_Key = "1100".
> > Now the strange thing happens if I try to run the following code:
> > Sub MyTest()
> > Dim MyString1 As String
> > Dim MyString2 As String
> > MyString1 = CStr(Session("Sec_ProgClient_Key"))
> > ...
> > MyString2 = CStr(Session("Sec_ProgUser_Gen"))
> > End Sub
> > It fails in line 'MyString2 = CStr(Session("Sec_ProgUser_Gen"))' with Cast
> > from type 'DBNull' to type 'String' is not valid.
> > I don't understand this. They are both the same, the only difference is
> the
> > length of the string. Help!
> > Additional Information:
> > The values for @.Sec_ProgUser_XXX are created in the stored procedure with
> a
> > statement like this:
> > SET @.Sec_ProgUser_Key = (SELECT Convert(varchar(1),Key_CanCreateKey) +
> > Convert(varchar(1),Key_CanCreateTransaction) +
> > Convert(varchar(1),Key_CanView) + Convert(varchar(1),Key_CanDelete) FROM
> > i2b_proguser_securityprofile WHERE SecurityProfileID = @.SecurityProfileID)
> > The datatype of the source columns used to be bit then changed them to
> > Integer as I thought this might cause the problem. (Although it shouldn't
> as
> > the values get converted to varchar without a problem in the stored
> > procedure. No fields contain NULL values, only 1 or 0.

Strange Error

Hello,

I am using ASP.NET 2.0 with SQL 2005 to save the profile.

Suddenly, out of nothing I got the following error:

The 'System.Web.Profile.SqlProfileProvider' requires adatabase schema compatible with schema version '1'. However, thecurrent database schema is not compatible with this version. You mayneed to either install a compatible schema with aspnet_regsql.exe(available in the framework installation directory), or upgrade theprovider to a newer version.

Description:Anunhandled exception occurred during the execution of the current webrequest. Please review the stack trace for more information about theerror and where it originated in the code.

Exception Details:System.Configuration.Provider.ProviderException:The 'System.Web.Profile.SqlProfileProvider' requires a database schemacompatible with schema version '1'. However, the current databaseschema is not compatible with this version. You may need to eitherinstall a compatible schema with aspnet_regsql.exe (available in theframework installation directory), or upgrade the provider to a newerversion.

Source Error:

Line 22: Public Overridable Property Contacts() As PR.Contacts
Line 23: Get
Line 24: Return CType(Me.GetPropertyValue("Contacts"),PR.Contacts)
Line 25: End Get
Line 26: Set


I have no idea what is going on.

I already deleted all the databases and added a few more but nothing ... I used aspnet_regsql.exe from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe.

What should I do?

Thanks,

Miguel

You are missing the schema entry in the aspnet_schemaversions table for your database, if you moved the db from one server to another using scripts you still need to add the entries in this table.

Open this table and see if anything is missing. (profile,1,true) is what you need.

-c


Hello,

I didn't move the database. This is on my computer and I created the databases using aspnet_regsql.exe.

I opened ScemaVersions database and I have this:

common1Truehealth monitoring1Truemembership1Truepersonalization1Trueprofile1Truerole manager1True

What might be going wrong here?

I started to get this error out of nothing. I really have no idea what might be the cause of it.

Thanks,

Miguel


Can you post the profile config xml from your web.config - remember to hide passwords! ;)

Hi,

Where is my profile code in Web.Config:

<!-- Profile -->
<profile enabled="true" defaultProvider="ProfileProvider" automaticSaveEnabled="true">

<!-- Profile Providers -->
<providers>
<clear/>
<add applicationName="AppName" connectionStringName="MyDatabase" name="ProfileProvider" type="System.Web.Profile.SqlProfileProvider"/>
</providers>

<!-- Profile Properties -->
<properties>
<add allowAnonymous="false" name="Collaborator" type="MyWebSite.Collaborator" serializeAs="Binary"/>
<add allowAnonymous="false" name="Contacts" type="MyWebSite.Contacts" serializeAs="Binary"/>
<add allowAnonymous="false" name="Options" type="MyWebSite.Options" serializeAs="Binary"/>
<add allowAnonymous="false" name="Personal" type="MyWebSite.Personal" serializeAs="Binary"/>
<add allowAnonymous="true" name="Settings" type="MyWebSite.Settings" serializeAs="Binary"/>
</properties>

</profile>

Any idea what might be going on?

Thanks,

Miguel


Ok some more questions - I see you're using custom types with a binary serializer - why? and did you change the class definitions for any of these custom types? If so and there was stored profile data, this would break your system since the serializer wouldn't be able to de-serialize the objects.

-c


maybe just something to try - but if you did change your class definitions - try deleting all the data in the profile table, it should re-serialize and might fix it.

-c


Hi,

Should I use other type?

Here is a class as example:

' Collaborator
<Serializable()> _
Public Class Collaborator

' -- [Properties] --------------

' Comments
Private _Comments As String
Public Property Comments() As String
Get
Return _Comments
End Get
Set(ByVal value As String)
_Comments = value
End Set
End Property ' Comments

' CurriculumVitae
Private _CurriculumVitae As String
Public Property CurriculumVitae() As String
Get
Return _CurriculumVitae
End Get
Set(ByVal value As String)
_CurriculumVitae = value
End Set
End Property ' CurriculumVitae
...

And by the way, suddenly I stopped getting the error.

This was really strange.

Thanks,

Miguel

Strange error

Hello everyone,

I have a C# web aplication that uses ASP.NET as FRONT END and for the Logical and Data Layers i have Webservices that connect to SQL and use stored procedures.

From time to time when i open my browser and run the application either for test or to show something to someone i get this Error

--> COPY PASTE <--

Server Error in '/cpin' Application.
------------------------

Server was unable to process request. --> General network error. Check your network documentation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Services.Protocols.SoapException: Server was unable to process request. --> General network error. Check your network documentation.

Source Error:

Line 297: [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.cpin.pt/webservices/GetLinguagens", RequestNamespace="http://www.cpin.pt/webservices", ResponseNamespace="http://www.cpin.pt/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
Line 298: public System.Data.DataSet GetLinguagens() {
Line 299: object[] results = this.Invoke("GetLinguagens", new object[0]);
Line 300: return ((System.Data.DataSet)(results[0]));
Line 301: }

Source File: f:\webserver\cpin\web references\core\reference.cs Line: 299

Stack Trace:

[SoapException: Server was unable to process request. --> General network error. Check your network documentation.]
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +1489
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +218
Cpin.Core.CoreWS.GetLinguagens() in f:\webserver\cpin\web references\core\reference.cs:299
Cpin.MainPage.Page_Load(Object sender, EventArgs e) in f:\webserver\cpin\default.aspx.cs:31
System.Web.UI.Control.OnLoad(EventArgs e) +67
System.Web.UI.Control.LoadRecursive() +35
System.Web.UI.Page.ProcessRequestMain() +731

------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573

--> END OF COPY PASTE <--

I can't figure out why i get this error :(

Just for the record if i refresh it either apears again or just works wonderfuly till next time...

All my network works fine... just this wierd error...

Don't know what to do. Anyone has an idea?

RegardsI had this same problem. Sometimes my page worked, othertimes it failed.

It turned out that I was compiling my app against a different version of the .NET framework than that used on the server to which I deployed my app.

So, check whether your local framework version is the same as that on the remote machine that is deploying your app (or exposing your web services, in this case).
Hello mate, thanks for your post.

Everything is running the version that is posted in the last line of the error.

:/ Any other ideas?
I don't have an answer, but I have three suggestions.

First, since a web service is, by definition, on a computer other than your own, you cannot presume that web service will always be available (unlike a local DLL which you can presume to be there). So, any web service requestsmust be wrapped in a Try/Catch exception handler ... with the Catch providing the response "web service currently unavailable". Particularly if, as you mention, you are showing your app/service to someone, a friendly error message is much more professional than an unhandled exception.

Second, the error message mentions an Asynchronous switch. Thinking along those lines, if your refreshing sometimes works and othertimes doesn't work, perhaps your app and your web service are getting out of synch? Microsoft'sApplication Architecture for .NET: Designing Applications and Services talks about controlling caching, synchronicity and messaging in web services. It's an incredibly helpful planning document, so download it for reference even if you find an easy fix for your current problem.

Third, your error message is SOAP-specific, so you might try asking your question atthis forum. I don't think this counts as a Getting Started newbie question :)

Thursday, March 22, 2012

Strange issue with Environment.NewLine in SQL

First off, apologies if this is in the wrong board.

I'm going to ramble a bit here in an attempt to get my thoughts together...

Background:

So I have this message board I've built using ASP.Net 2.0 and SQL 2005. I'd link you to it, but the particular site in question is a bit of a free for all so I can't guarantee you won't find something offensive =P.

Anyways, the important thing to note is that posts are typed into a multiline textbox, and saved 'as is' in the relevant SQL table as varchar. When a topic is displayed, this text is converted into HTML: Environment.NewLine -> <br />, weird messageboard tags into HTML (bold, italic, etc.), and so on.

Now this is all fine and dandy but lately a weird issue has came up.

Issue:

The odd time, when a particular person makes a post, his NewLine characters get lost somewhere. What I mean is he'll type something with pretty paragraph breaks and nice formatting and then it'll be displayed as a solid block of text.

But here's where things get funky - if I click to edit his post (at which point the text is displayed 'as is' from the SQL table into another textbox), it displays as it should, with the line breaks. If I save the changes without altering the text at all, his post will now display properly. I can also quote his single-block-of-text post and it will display as multiple paragraphs within my own post.

All I can figure is that maybe something strange is happening for different users as they saved their posts.

Some things to note:

I looked through the SQL tables at three identical posts, one posted by user A, who had his post turn into a single block of text, one by me, whose post displayed properly, and another consisting of user A's post copy/pasted by me (just to ensure I didn't miss anything when retyping his post). Again, this last post displayed properly.

The hexadecimal code for the line-breaks in my post was 0x0D 0x0A, which corresponds to the CRLF code for Windows. Makes sense since I'm using Windows. This was again the case for my second post, the copy/pasted version of User A's original post. Though when I look at his post, the line-break characters come up as 0x0A, which is the LF code for users running a Mac. This makes less sense because I know the guy is running Windows.

But maybe I'm overthinking this and I should be using a unicode variable type in the SQL? Any suggestions would be welcome.

Cheers

apedrape83:

The hexadecimal code for the line-breaks in my post was 0x0D 0x0A, which corresponds to the CRLF code for Windows. Makes sense since I'm using Windows. This was again the case for my second post, the copy/pasted version of User A's original post. Though when I look at his post, the line-break characters come up as 0x0A, which is the LF code for users running a Mac. This makes less sense because I know the guy is running Windows.

You know he is using Windows because you have observed this with your own eyes? Or because he told you? Maybe he's running windows on a Mac, and this is a "feature".


Oh snap, just found this:http://forums.asp.net/p/1186555/2027418.aspx

He's running windows (he sent me screenshots while I was requesting his assistance in debugging), so yeah, saw it with my own eyes more or less. BUT, he's also running FireFox and doesn't have a problem in IE7. I overlooked this because it worked fine on my own FireFox, which is a different version than his.

I'm going to have to read more into this issue with FireFox and see if the way it chooses to save NewLines explains the truncated hex values I described.


Anyways, the problem was solved by grabbing all of the '\r\n' breaks out of the string as put in by IE7 and replacing them with the html followed by grabbing the leftover '\n' breaks used by other browsers as the NewLine in a textbox and replacing those as opposed to replacing the Environment.NewLine directly.

Strange Listbox Behavior when using a Datasource

I have 2 Listboxes placed nexto each other with buttons bellow them to Add, Add All, Remove, Remove All.

Both list boxes use a select query from a SQL 2005 table to get their values.

Thats about up to where things behave normally. If I click Add, it should remove the selected item from listbox1 and add it to listbox2. It adds the item to listbox2, but doesnt remove it from listbox1. If however, I click remove on the newly added item, it will remove that item and place it back in listbox1, except there are now two entries in listbox1 with the same name/value. The add all and remove all buttons cause the browser to "get stuck", im assuming because it gets stuck in a endless loop because it can never remove the values from listbox1.

Any help would be GREATLY appreciated, this has been driving me up the wall for the better part of the day.

Some code snippets:

<asp:ListBox ID="AvailableManufacturers" runat="server" DataSourceID="SqlDataSource1" DataTextField="manufacturerName"
DataValueField="manufacturerID" SelectionMode="Multiple"></asp:ListBox>
<asp:ListBox ID="CurrentManufacturers" runat="server" DataSourceID="SqlDataSource2" DataTextField="manufacturerName"
DataValueField="manufacturerID" SelectionMode="Multiple"></asp:ListBox>

<asp:Button ID="RemoveAll" runat="server" Text="<<" OnClick="RemoveAll_Click"/>
<asp:Button ID="Remove" runat="server" Text="<" OnClick="Remove_Click"/>

<asp:Button ID="Add" runat="server" OnClick="Add_Click" Text=">"/>
<asp:Button ID="AddAll" runat="server" OnClick="AddAll_Click" Text=">>"/><br />
<br />
<asp:Button ID="Update" runat="server" BackColor="#FFFFC0" BorderColor="Maroon"
BorderStyle='Ridge' ForeColor='Red' Text='Update' />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connectionString1 %>"
SelectCommand="SELECT manufacturerID, manufacturerName FROM manufacturers WHERE (manufacturerID NOT IN (SELECT DISTINCT manufacturerID FROM dealerManufacturers WHERE (dealerUsername = @dotnet.itags.org.dealerUsername)))">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:connectionString1 %>"
SelectCommand="SELECT manufacturerID, manufacturerName FROM manufacturers WHERE (manufacturerID IN (SELECT DISTINCT manufacturerID FROM dealerManufacturers WHERE (dealerUsername = @dotnet.itags.org.dealerUsername)))">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters.Add("dealerUsername", TypeCode.String, User.Identity.Name);
SqlDataSource2.SelectParameters.Add("dealerUsername", TypeCode.String, User.Identity.Name);

}

protected void Add_Click(Object Src, EventArgs E)
{

if (AvailableManufacturers.SelectedIndex != -1)
{

CurrentManufacturers.Items.Add(new ListItem(AvailableManufacturers.SelectedItem.Text));
AvailableManufacturers.Items.Remove(AvailableManufacturers.SelectedItem.Text);
}
}

protected void AddAll_Click(Object Src, EventArgs E)
{

while (AvailableManufacturers.Items.Count != 0)
{

CurrentManufacturers.Items.Add(new ListItem(AvailableManufacturers.Items[0].Text));
AvailableManufacturers.Items.Remove(AvailableManufacturers.Items[0].Text);
}
}

protected void Remove_Click(Object Src, EventArgs E)
{

if (CurrentManufacturers.SelectedIndex != -1)
{

AvailableManufacturers.Items.Add(new ListItem(CurrentManufacturers.SelectedItem.Text));
CurrentManufacturers.Items.Remove(CurrentManufacturers.SelectedItem.Text);
}
}

protected void RemoveAll_Click(Object Src, EventArgs E)
{

while (CurrentManufacturers.Items.Count != 0)
{

AvailableManufacturers.Items.Add(new ListItem(CurrentManufacturers.Items[0].Text));
CurrentManufacturers.Items.Remove(CurrentManufacturers.Items[0].Text);
}
}

You have to iterate in reverse order (bottom to top) through all the selected items of the first listbox and add them to the second listbox and then remove them from the first listbox. Doing in reverse order is very important since you have to remove them based on an index. If you do it in a normal order, then after you remove the first item (let's say index 3) then all the indexes change and you might get an index outside of the boundaries exception.

Having that said you will implement the add button this way:

protected void Add_Click(object sender, EventArgs e) {for (int i = AvailableManufacturers.Items.Count - 1; i >= 0; i--) {if (AvailableManufacturers.Items[i].Selected)//if this item was selected { CurrentManufacturers.Items.Add(AvailableManufacturers.Items[i].Text); AvailableManufacturers.Items.RemoveAt(i); } } }
The same thing applies for the remove, but with the opposite listboxes and for the remove all and add all you do the same thing, but doin't check for selected.

..and if that drives you nuts, there are components likeEasyListBox and Metabuilders'DualList that will do all this for you :)

Strange NULL value behaviour / RequiredFieldValidator

Hi everyone,

Im puzzled by a NULL behaviour in SQL 2000 server.

There is a column in the table that does not allow NULL.

During data mining, the staff noted that, for that particular column, there
are a few records that are empty.

I do not specifically know whether they are "alt + 0160" character.

What are the reasons that can cause this to happen?

Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
control to ensure that the field is compulsory

On the application scripting, I've the following to cleanse the data before
the data goes into the database:

cmd.Parameters.Add("@dotnet.itags.org.STREET_NAME", Data.SqlDbType.VarChar)
cmd.Parameters("@dotnet.itags.org.STREET_NAME").Value =
ReplaceSingleQuote(streetname.Text.Trim())

The function is:

Public Shared Function ReplaceSingleQuote(ByVal x As String)

If x = "" Then
Return x
End If

x = x.Replace("'", "''")
Return x

End Function

Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.comHowdy,

I see you're using Parameters so you don't need to replace any characters as
SqlParameter is responsible for that. It's only required if you build queries
through concatenation. I suspect all single quotes have been turned to doule
quotes (see it in the database). Anyway, it seems there's something wrong
with your validation as empty entries are submited.

Regards
--
Milosz

"Eric Layman" wrote:

Quote:

Originally Posted by

Hi everyone,
>
Im puzzled by a NULL behaviour in SQL 2000 server.
>
There is a column in the table that does not allow NULL.
>
During data mining, the staff noted that, for that particular column, there
are a few records that are empty.
>
I do not specifically know whether they are "alt + 0160" character.
>
What are the reasons that can cause this to happen?
>
>
Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
control to ensure that the field is compulsory
>
On the application scripting, I've the following to cleanse the data before
the data goes into the database:
>
cmd.Parameters.Add("@.STREET_NAME", Data.SqlDbType.VarChar)
cmd.Parameters("@.STREET_NAME").Value =
ReplaceSingleQuote(streetname.Text.Trim())
>
The function is:
>
Public Shared Function ReplaceSingleQuote(ByVal x As String)
>
If x = "" Then
Return x
End If
>
x = x.Replace("'", "''")
Return x
>
End Function
>
>
>
>
>
Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.com
>


Thanks for the reply.

That's very weird.

I have no idea how to account for the blank columns!

She showed me the sql commands and that column is specifically set to NOT
NULL

She asked me "How did you do that?"

"Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.plwrote in message
news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...

Quote:

Originally Posted by

Howdy,
>
I see you're using Parameters so you don't need to replace any characters
as
SqlParameter is responsible for that. It's only required if you build
queries
through concatenation. I suspect all single quotes have been turned to
doule
quotes (see it in the database). Anyway, it seems there's something wrong
with your validation as empty entries are submited.
>
Regards
--
Milosz
>
>
"Eric Layman" wrote:
>

Quote:

Originally Posted by

>Hi everyone,
>>
>Im puzzled by a NULL behaviour in SQL 2000 server.
>>
>There is a column in the table that does not allow NULL.
>>
>During data mining, the staff noted that, for that particular column,
>there
>are a few records that are empty.
>>
>I do not specifically know whether they are "alt + 0160" character.
>>
>What are the reasons that can cause this to happen?
>>
>>
>Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
>control to ensure that the field is compulsory
>>
>On the application scripting, I've the following to cleanse the data
>before
>the data goes into the database:
>>
>cmd.Parameters.Add("@.STREET_NAME", Data.SqlDbType.VarChar)
>cmd.Parameters("@.STREET_NAME").Value =
>ReplaceSingleQuote(streetname.Text.Trim())
>>
>The function is:
>>
> Public Shared Function ReplaceSingleQuote(ByVal x As String)
>>
> If x = "" Then
> Return x
> End If
>>
> x = x.Replace("'", "''")
> Return x
>>
> End Function
>>
>>
>>
>>
>>
> Posted Via Usenet.com Premium Usenet Newsgroup Services
>------------------
> ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
>------------------
> http://www.usenet.com
>>


>


Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.com
Hi Eric again,

Correct me if I'm wrong but you (or she) is confusing empty string with
NULL. NULL is a special value that simply indicates nothing is assigned,
whilst empty string is a correct value. Setting NOT NULL constraint to a
varchar column means NULL value is not allowed, but any other values (like
empty string '') are. Also check if there is a default value set for this
column. Anyway, from the code you posted, I suspect, there aren't data access
layer or business logic layers as you assign values directly from user
controls. This may indicate, operations on the table are performed in several
places differently (different logic?). In addition, do you use stored
procedures or plain text queries? If SPs, please confirm there is no logic
inside that inserts empty string in some cases. And the last tip, have you
checked if there are any triggers created on this table?

Regards

--
Milosz

"Eric Layman" wrote:

Quote:

Originally Posted by

Thanks for the reply.
>
That's very weird.
>
I have no idea how to account for the blank columns!
>
She showed me the sql commands and that column is specifically set to NOT
NULL
>
She asked me "How did you do that?"
>
>
>
"Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.plwrote in message
news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...

Quote:

Originally Posted by

Howdy,

I see you're using Parameters so you don't need to replace any characters
as
SqlParameter is responsible for that. It's only required if you build
queries
through concatenation. I suspect all single quotes have been turned to
doule
quotes (see it in the database). Anyway, it seems there's something wrong
with your validation as empty entries are submited.

Regards
--
Milosz

"Eric Layman" wrote:

Quote:

Originally Posted by

Hi everyone,
>
Im puzzled by a NULL behaviour in SQL 2000 server.
>
There is a column in the table that does not allow NULL.
>
During data mining, the staff noted that, for that particular column,
there
are a few records that are empty.
>
I do not specifically know whether they are "alt + 0160" character.
>
What are the reasons that can cause this to happen?
>
>
Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
control to ensure that the field is compulsory
>
On the application scripting, I've the following to cleanse the data
before
the data goes into the database:
>
cmd.Parameters.Add("@.STREET_NAME", Data.SqlDbType.VarChar)
cmd.Parameters("@.STREET_NAME").Value =
ReplaceSingleQuote(streetname.Text.Trim())
>
The function is:
>
Public Shared Function ReplaceSingleQuote(ByVal x As String)
>
If x = "" Then
Return x
End If
>
x = x.Replace("'", "''")
Return x
>
End Function
>
>
>
>
>
Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.com
>



>
>
>
Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.com
>


Run a test to see if there are actually NULLs in that column. Run the
following query:

SELECT *
FROM MyTable
WHERE MyColumn IS NULL

If you return rows then you have some NULLs in there and we'll need to
investigate how you got NULLs into a non-nullable column. If no rows are
returned then the column does not contain NULLs, and you need to determine
how you got zero-length strings into the column if you're not expecting them
to be there. If zero-length strings are being stored but are not
acceptable, you can add a check constraint like the following to the column:

CHECK(LEN(MyColumn) 0)

"Eric Layman" <namyalcire[at no spam]gmail.comwrote in message
news:1175766804_1545@.sp6iad.superfeed.net...

Quote:

Originally Posted by

Thanks for the reply.
>
That's very weird.
>
I have no idea how to account for the blank columns!
>
She showed me the sql commands and that column is specifically set to NOT
NULL
>
She asked me "How did you do that?"
>
>
>
"Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.plwrote in message
news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...

Quote:

Originally Posted by

>Howdy,
>>
>I see you're using Parameters so you don't need to replace any characters
>as
>SqlParameter is responsible for that. It's only required if you build
>queries
>through concatenation. I suspect all single quotes have been turned to
>doule
>quotes (see it in the database). Anyway, it seems there's something wrong
>with your validation as empty entries are submited.
>>
>Regards
>--
>Milosz
>>
>>
>"Eric Layman" wrote:
>>

Quote:

Originally Posted by

>>Hi everyone,
>>>
>>Im puzzled by a NULL behaviour in SQL 2000 server.
>>>
>>There is a column in the table that does not allow NULL.
>>>
>>During data mining, the staff noted that, for that particular column,
>>there
>>are a few records that are empty.
>>>
>>I do not specifically know whether they are "alt + 0160" character.
>>>
>>What are the reasons that can cause this to happen?
>>>
>>>
>>Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
>>control to ensure that the field is compulsory
>>>
>>On the application scripting, I've the following to cleanse the data
>>before
>>the data goes into the database:
>>>
>>cmd.Parameters.Add("@.STREET_NAME", Data.SqlDbType.VarChar)
>>cmd.Parameters("@.STREET_NAME").Value =
>>ReplaceSingleQuote(streetname.Text.Trim())
>>>
>>The function is:
>>>
>> Public Shared Function ReplaceSingleQuote(ByVal x As String)
>>>
>> If x = "" Then
>> Return x
>> End If
>>>
>> x = x.Replace("'", "''")
>> Return x
>>>
>> End Function
>>>
>>>
>>>
>>>
>>>
>> Posted Via Usenet.com Premium Usenet Newsgroup Services
>>------------------
>> ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
>>------------------
>> http://www.usenet.com
>>>


>>


>
>
>
Posted Via Usenet.com Premium Usenet Newsgroup Services
------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
------------------
http://www.usenet.com

Strange NULL value behaviour / RequiredFieldValidator

Hi everyone,
Im puzzled by a NULL behaviour in SQL 2000 server.
There is a column in the table that does not allow NULL.
During data mining, the staff noted that, for that particular column, there
are a few records that are empty.
I do not specifically know whether they are "alt + 0160" character.
What are the reasons that can cause this to happen?
Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
control to ensure that the field is compulsory
On the application scripting, I've the following to cleanse the data before
the data goes into the database:
cmd.Parameters.Add("@dotnet.itags.org.STREET_NAME", Data.SqlDbType.VarChar)
cmd.Parameters("@dotnet.itags.org.STREET_NAME").Value =
ReplaceSingleQuote(streetname.Text.Trim())
The function is:
Public Shared Function ReplaceSingleQuote(ByVal x As String)
If x = "" Then
Return x
End If
x = x.Replace("'", "''")
Return x
End Function
Posted Via mcse.ms Premium Usenet Newsgroup Services
----
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----
http://www.mcse.msHowdy,
I see you're using Parameters so you don't need to replace any characters as
SqlParameter is responsible for that. It's only required if you build querie
s
through concatenation. I suspect all single quotes have been turned to doule
quotes (see it in the database). Anyway, it seems there's something wrong
with your validation as empty entries are submited.
Regards
--
Milosz
"Eric Layman" wrote:

> Hi everyone,
> Im puzzled by a NULL behaviour in SQL 2000 server.
> There is a column in the table that does not allow NULL.
> During data mining, the staff noted that, for that particular column, ther
e
> are a few records that are empty.
> I do not specifically know whether they are "alt + 0160" character.
> What are the reasons that can cause this to happen?
>
> Validation front end, I've used ASP.NET's REQUIREDFIELDVALIDATOR on the
> control to ensure that the field is compulsory
> On the application scripting, I've the following to cleanse the data befor
e
> the data goes into the database:
> cmd.Parameters.Add("@.STREET_NAME", Data.SqlDbType.VarChar)
> cmd.Parameters("@.STREET_NAME").Value =
> ReplaceSingleQuote(streetname.Text.Trim())
> The function is:
> Public Shared Function ReplaceSingleQuote(ByVal x As String)
> If x = "" Then
> Return x
> End If
> x = x.Replace("'", "''")
> Return x
> End Function
>
>
> Posted Via mcse.ms Premium Usenet Newsgroup Services
> ----
> ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
> ----
> http://www.mcse.ms
>
Thanks for the reply.
That's very weird.
I have no idea how to account for the blank columns!
She showed me the sql commands and that column is specifically set to NOT
NULL
She asked me "How did you do that?"
"Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.pl> wrote in message
news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...
> Howdy,
> I see you're using Parameters so you don't need to replace any characters
> as
> SqlParameter is responsible for that. It's only required if you build
> queries
> through concatenation. I suspect all single quotes have been turned to
> doule
> quotes (see it in the database). Anyway, it seems there's something wrong
> with your validation as empty entries are submited.
> Regards
> --
> Milosz
>
> "Eric Layman" wrote:
>
>
Posted Via mcse.ms Premium Usenet Newsgroup Services
----
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----
http://www.mcse.ms
Hi Eric again,
Correct me if I’m wrong but you (or she) is confusing empty string with
NULL. NULL is a special value that simply indicates nothing is assigned,
whilst empty string is a correct value. Setting NOT NULL constraint to a
varchar column means NULL value is not allowed, but any other values (like
empty string '') are. Also check if there is a default value set for this
column. Anyway, from the code you posted, I suspect, there aren’t data acc
ess
layer or business logic layers as you assign values directly from user
controls. This may indicate, operations on the table are performed in severa
l
places differently (different logic?). In addition, do you use stored
procedures or plain text queries? If SPs, please confirm there is no logic
inside that inserts empty string in some cases. And the last tip, have you
checked if there are any triggers created on this table?
Regards
Milosz
"Eric Layman" wrote:

> Thanks for the reply.
> That's very weird.
> I have no idea how to account for the blank columns!
> She showed me the sql commands and that column is specifically set to NOT
> NULL
> She asked me "How did you do that?"
>
> "Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.pl> wrote in message
> news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...
>
> Posted Via mcse.ms Premium Usenet Newsgroup Services
> ----
> ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
> ----
> http://www.mcse.ms
>
Run a test to see if there are actually NULLs in that column. Run the
following query:
SELECT *
FROM MyTable
WHERE MyColumn IS NULL
If you return rows then you have some NULLs in there and we'll need to
investigate how you got NULLs into a non-nullable column. If no rows are
returned then the column does not contain NULLs, and you need to determine
how you got zero-length strings into the column if you're not expecting them
to be there. If zero-length strings are being stored but are not
acceptable, you can add a check constraint like the following to the column:
CHECK(LEN(MyColumn) > 0)
"Eric Layman" <namyalcire[at no spam]gmail.com> wrote in message
news:1175766804_1545@.sp6iad.superfeed.net...
> Thanks for the reply.
> That's very weird.
> I have no idea how to account for the blank columns!
> She showed me the sql commands and that column is specifically set to NOT
> NULL
> She asked me "How did you do that?"
>
> "Milosz Skalecki [MCAD]" <mily242@.DONTLIKESPAMwp.pl> wrote in message
> news:F8096D27-F0D9-430B-9166-75518B2F4F98@.microsoft.com...
>
> Posted Via mcse.ms Premium Usenet Newsgroup Services
> ----
> ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
> ----
> http://www.mcse.ms

Tuesday, March 13, 2012

strange postback/ SQL problem

I have a datagrid which populates from a SQLDataSource. The page is to default to filter the data as the user that is logged on but there is a drop down menu to select to filter by another user. The drop down menu is autopostback and I have the following code in my on page load event:

 Dim teamleader As String Dim currentyear As String = DateTime.Now.Year 'find the current year
 If Page.IsPostBack Then 'pickup the selected teamleader from drop down menu Dim placeholder As ContentPlaceHolder = CType(Master.FindControl("bodybox"), ContentPlaceHolder) Dim thelist As DropDownList = CType(placeholder.FindControl("dropdownlist1"), DropDownList) teamleader = thelist.Text.ToString 'default to logged in persons name Else teamleader = User.Identity.Name.ToString End If teamdata.SelectCommand = "SELECT username, name, holiday_entitlement_" & currentyear & " as holiday_entitlement, holiday_used_" & currentyear & " as holiday_used, holiday_entitlement_" & currentyear & " - holiday_used_" & currentyear & " AS holiday_left FROM holiday.reps WHERE (teamleader = '" & teamleader & "') AND (hasleft = 'N') ORDER BY name;"

The problem is that if the page isnt postback and the user logged in is "ch12" then I get a populated datagrid. If however the page is a postback the datagrid is showing the empty template. I have looked at the SQL the page is generating and as far as I see they are identical:

Not postback:

SELECT username,name, holiday_entitlement_2006as holiday_entitlement, holiday_used_2006as holiday_used, holiday_entitlement_2006 - holiday_used_2006AS holiday_leftFROM holiday.repsWHERE (teamleader ='ch12')AND (hasleft ='N')ORDER BY name;

Is postback:

SELECT username,name, holiday_entitlement_2006as holiday_entitlement, holiday_used_2006as holiday_used, holiday_entitlement_2006 - holiday_used_2006AS holiday_leftFROM holiday.repsWHERE (teamleader ='ch12')AND (hasleft ='N')ORDER BY name;

Any ideas why one datagrid is appearing empty and the other populated when the select command being generated appears to be identical?

Anyone have any idea on this at all?

Set the datasource to the Grid in the SelectedIndexChanged event of the dropdownlist. Make sure you populate the dropdownlist with PostBack check in the page_load.

page_load() {

if (!Page.IsPostBack) {
// load the dropdownlist
// assign datasource and bind grid -- default
}
}

selectedIndexChanged event of dropdownlist {
// assign datasource and bind grid
}

Thanks


Have worked out the problem but not the fix. I am correctly creating the new sqldatasource1.selectcommand on the postback however the datagrid is always displaying the results from the original page load.

How do I make the page discard the original results and re run the query on each page load (in VB)?

Many thanks



1<%@. Page Language="VB" MasterPageFile="~/loggedin/the.master" %>23<script runat="server">45Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs6Dim teamleader as string7Dim currentyearAs String = DateTime.Now.Year8If Not User.IsInRole("teamleader")Then9 Try10 Dim placeholderAs ContentPlaceHolder =CType(Master.FindControl("bodybox"), ContentPlaceHolder)11Dim thelistAs DropDownList =CType(placeholder.FindControl("dropdownlist1"), DropDownList)12 teamleader = thelist.Text.ToString'default to logged in persons name13If teamleader ="."Then teamleader = User.Identity.Name.ToString14Catch exAs Exception15 teamleader = User.Identity.Name.ToString16End Try17 Else18 teamleader = User.Identity.Name.ToString19End If2021 teamdata.SelectCommand ="SELECT username, name, holiday_entitlement_" & currentyear &" as holiday_entitlement, holiday_used_" & currentyear &" as holiday_used, holiday_entitlement_" & currentyear &" - holiday_used_" & currentyear &" AS holiday_left FROM holiday.reps WHERE (teamleader ='" & teamleader & "') AND (hasleft = 'N') ORDER BY name;"22 End Sub23</script>2425<asp:Content ID="Content1" ContentPlaceHolderID="bodybox" Runat="Server">2627 <asp:DropDownList ID="dropdownlist1" runat="server" DataSourceID="teamleaderlist" DataTextField="Username" DataValueField="Username" AutoPostBack="true" AppendDataBoundItems="True" >28 <asp:ListItem Selected="True" Value="." Text=""></asp:ListItem></asp:DropDownList>29 <asp:SqlDataSource ID="teamleaderlist" runat="server" ConnectionString="<%$ ConnectionStrings:holidaybookingConnectionString %>" ProviderName="<%$ ConnectionStrings:holidaybookingConnectionString.ProviderName %>"></asp:SqlDataSource>3031<asp:SqlDataSource ID="teamdata" runat="server" ConnectionString="<%$ ConnectionStrings:holidaybookingConnectionString %>" ProviderName="<%$ ConnectionStrings:holidaybookingConnectionString.ProviderName %>" ></asp:SqlDataSource>3233<asp:GridView ID="teamview" runat="server" AllowSorting="True"34 DataKeyNames="username" DataSourceID="teamdata" CellPadding="5" GridLines="None" HorizontalAlign="Center">35 <EmptyDataTemplate>36 There are currently no Reps to display37 </EmptyDataTemplate>38 </asp:GridView>39</asp:content>
Above is the code for the problem area - I havent posted the code generating the SQL for the dropdownmenu as it is rather long and convoluted and is working fine.

Post your code!

Thanks


DropDownList onselectedIndexchanged will cause postback and your page_load code executes everytime it is posted. So you are getting the same values. Add a postback check in the page_load. Where in the page_load you are binding the grid?? In the SelectIndexChanged event again you need to write the code for the selected userRole


5Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs
6Dim teamleader as string
7Dim currentyearAs String = DateTime.Now.Year
If Not Page.IsPostBack Then
8If Not User.IsInRole("teamleader")Then
9 Try
10 Dim placeholderAs ContentPlaceHolder =CType(Master.FindControl("bodybox"), ContentPlaceHolder)
11Dim thelistAs DropDownList =CType(placeholder.FindControl("dropdownlist1"), DropDownList)
12 teamleader = thelist.Text.ToString'default to logged in persons name
13If teamleader ="."Then teamleader = User.Identity.Name.ToString
14Catch exAs Exception
15 teamleader = User.Identity.Name.ToString
16End Try
17 Else
18 teamleader = User.Identity.Name.ToString
19End If
20
21 teamdata.SelectCommand ="SELECT username, name, holiday_entitlement_" & currentyear &" as holiday_entitlement, holiday_used_" & currentyear &" as holiday_used, holiday_entitlement_" & currentyear &" - holiday_used_" & currentyear &" AS holiday_left FROM holiday.reps WHERE (teamleader ='" & teamleader & "') AND (hasleft = 'N') ORDER BY name;"
End If
protected void DropdownList1_SelectedIndexChanged(object sender, EventArgs e)
{

6Dim teamleader as string
7Dim currentyearAs String = DateTime.Now.Year
8If Not User.IsInRole("teamleader")Then
9 Try
10 Dim placeholderAs ContentPlaceHolder =CType(Master.FindControl("bodybox"), ContentPlaceHolder)
11Dim thelistAs DropDownList =CType(placeholder.FindControl("dropdownlist1"), DropDownList)
12 teamleader = thelist.Text.ToString'default to logged in persons name
13If teamleader ="."Then teamleader = User.Identity.Name.ToString
14Catch exAs Exception
15 teamleader = User.Identity.Name.ToString
16End Try
17 Else
18 teamleader = User.Identity.Name.ToString
19End If
20
21 teamdata.SelectCommand ="SELECT username, name, holiday_entitlement_" & currentyear &" as holiday_entitlement, holiday_used_" & currentyear &" as holiday_used, holiday_entitlement_" & currentyear &" - holiday_used_" & currentyear &" AS holiday_left FROM holiday.reps WHERE (teamleader ='" & teamleader & "') AND (hasleft = 'N') ORDER BY name;"

}
Also try using the dropDownList.SelectedItem.Value rather the .Text when selecting values fromthe dropdownlist.

Thanks
Many thanks, all works great now