Monday, March 19, 2012

creating SQLDataSource programmatically?

Hello. Im trying to create an SQLDataSource control programmatically. I need to do this because I want to do some stuff on my MasterPage's 'Page_Init' event.

heres my code (Master.master.vb):

Protected Sub Page_Init(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Init lblUser.Text = Page.User.Identity.NameDim PUserAs New ControlParameter PUser.ControlID ="lblUser" PUser.Name ="LoginName" PUser.PropertyName ="Text" PUser.Type = TypeCode.String PUser.DefaultValue = Page.User.Identity.NameDim SQLDS_LoginAs New SqlDataSource SQLDS_Login.ID ="SQLDS_Login" SQLDS_Login.ConnectionString ="I put conection string here. How do I use the one on my web.config?" SQLDS_Login.SelectCommand ="SELECT [LoginID], [LoginName], [Role], [Status] FROM [myLogin] WHERE ([LoginName] = @.LoginName)" SQLDS_Login.SelectParameters.Add(PUser) SQLDS_Login.SelectCommandType = SqlDataSourceCommandType.Text GridView1.DataSource = SQLDS_Login GridView1.DataBind()End Sub

When i run, i get this error message:

The SqlDataSource control 'SQLDS_Login' does not have a naming container. Ensure that the control is added to the page before calling DataBind.

I never had any problem with Inserts, Updates and Deleting, but I have never made it work for Select when doing it programmatically.

Can you help me with this?

as the error states you need to add it to the page i.e. me.controls.add(SQLDS_Login) [or if you're doing it from a page that uses that for a master then me.master.controls.add(SQLDS_login)

No comments:

Post a Comment