I've got this code which works to populate a second dropdownlist based on what's in the first one (in the page's Page_Init event):
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
. . .
'Populate the Units dropdown
Dim unitsDT As DataTable
sql = "Select distinct unit from masterunits where abs(active) = 1"
retDS = sqlDAL.runSQLDataSet(sql)
unitsDT = retDS.Tables(0)
DropDownListUnits.DataSource = unitsDT
DropDownListUnits.DataTextField = "unit"
DropDownListUnits.DataValueField = "unit"
DropDownListUnits.DataBind()
'Populate the Members dropdown based on Unit selected
'Dim selectedUnit As String = DropDownListUnits.Text
Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
Dim membersDT As DataTable
sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
. . .
End Sub
...I need to also update the second dropdown any time the first one changes, so have this code:
Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
DropDownListMembers.Items.Clear
DropDownListCustomers.Items.Clear
Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
Dim membersDT As DataTable
Dim retDS As DataSet
Dim sql As String = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
End Sub
...but it doesn't work - selecting a different unit from DropDownListUnits does not change what is in DropDownListMembers.
Apparently this:
Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
...is not retrieving the new value selected from DropDownListUnits to selectedUnit.
I even added this, for debugging purposes:
Label2.Text = selectedUnit
...but Label2 never changes.
What am I doing wrong here?
UPDATE
Based on this, I also tried this:
Dim selectedUnit As String = DropDownListUnits.SelectedItem.ToString()
...but it makes no difference.
UPDATE 2
The event is apparently not even firing. This code:
Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
Label2.Text = "it fired"
. . .
...shows no change to Label2's text...
UPDATE 3
When I tried this as the first line in the Page_Init event:
If Not IsPostBack Then Exit Sub
...it doesn't even run once.
I already had a similar thing in there:
Dim PageAlreadyInitted As Boolean = False
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If PageAlreadyInitted = True Then Exit Sub
PageAlreadyInitted = True
. . .
UPDATE 4
Based on the last comment, I tried this in the Page_Init:
If Page.IsPostBack = True Then Exit Sub
...and it makes no difference - I still get no result from the DropDownListUnits_SelectedIndexChanged event; it apparently is not fired as Label2 does not change to "it fired", as it should:
Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
Label2.Text = "it fired"
UPDATE 5
This is more messed up than Keith Richards' hair after he fell out of the coconut palm on his noggin: I try to access the value displaying in a dropdownlist, and it gives me the wrong value.
Here's the code to populate the dropdownlists:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If PageAlreadyInitted = True Then Exit Sub
If Page.IsPostBack = True Then Exit Sub
PageAlreadyInitted = True
Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
'Populate the Units dropdown
Dim unitsDT As DataTable
Dim sql As String = "Select distinct mu.unit from masterunits mu left join MasterUnitsProjSales mps on mps.Unit = mu.Unit where abs(active) = 1 and mps.NewBiz != 0 order by mu.unit"
Dim retDS As DataSet = sqlDAL.runSQLDataSet(sql)
unitsDT = retDS.Tables(0)
DropDownListUnits.DataSource = unitsDT
DropDownListUnits.DataTextField = "unit"
DropDownListUnits.DataValueField = "unit"
DropDownListUnits.DataBind()
'Populate the Members dropdown - TODO: Call this when Unit changes, too
Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
Dim membersDT As DataTable
sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
'Populate the Customers dropdown - TODO: Call this when Member changes, too
Dim selectedMember As String = DropDownListMembers.SelectedItem.Value
Dim customersDT As DataTable
sql = "select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '" + selectedMember + "' order by companyname"
retDS = sqlDAL.runSQLDataSet(sql)
customersDT = retDS.Tables(0)
DropDownListCustomers.DataSource = customersDT
DropDownListCustomers.DataTextField = "companyname"
DropDownListCustomers.DataValueField = "companyname"
DropDownListCustomers.DataBind()
sqlDAL.Dispose()
End Sub
Here's what I see:
Note that "Applebees" is the unit displaying (I didn't select it - it is the first item in the collection, and displays by default).
Yet when I mash the button, the value stored in the database for Unit is "Abuelos" rather than "Applebees." Not only is this frustrating, it is also bizarre in the extreme, as "Abuelos" does not even exist in the collection of items:
Here's the code that's trying to get the value, for updating and inserting records in the database:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PROSQL05;DATABASE=cpsdata;UID=sa;PWD=sqlsql"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Existing', EndDate = #DateTimeYesterday, ChangedOn = #CurrentDateTime WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim insertDML As String = "INSERT INTO CustomerCategoryLog (MemberNo, Unit, Custno, Category, Subcategory, BeginDate, ChangedBy, ChangedOn) VALUES (#MemberNo_Insert, #Unit_Insert, #CustNo_Insert, #Category, #Subcategory, #BeginDate, #ChangedBy, #ChangedOn)"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
coName = DropDownListCustomers.SelectedItem.ToString()
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
cmd.Parameters.Add("#DateTimeYesterday", SqlDbType.DateTime).Value = DateTime.Today.AddDays(-1)
cmd.Parameters.Add("#CurrentDateTime", SqlDbType.DateTime).Value = Date.Now
conn.Open()
cmd.ExecuteScalar()
End Using
' Now insert a new record with "Existing" categories and Now as the BeginDate
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(insertDML, conn)
cmd.Parameters.Add("#MemberNo_Insert", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#Unit_Insert", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#CustNo_Insert", SqlDbType.VarChar, 50).Value = _CustNo
cmd.Parameters.Add("#Category", SqlDbType.VarChar, 50).Value = "Existing"
cmd.Parameters.Add("#Subcategory", SqlDbType.VarChar, 50).Value = "Existing"
cmd.Parameters.Add("#BeginDate", SqlDbType.DateTime).Value = DateTime.Today
cmd.Parameters.Add("#ChangedBy", SqlDbType.VarChar, 50).Value = Environment.UserName
cmd.Parameters.Add("#ChangedOn", SqlDbType.DateTime).Value = Date.Now
conn.Open()
cmd.ExecuteScalar()
End Using
End Sub
Here's what's inserted and updated in the database:
So as you can see, "Abuelos" is the Unit value, although it should be "Applebees" - what the Hec Ramsey !?!
This actually does work, apparently:
_Unit = DropDownListUnits.SelectedItem.ToString()
_MemberNo = DropDownListMembers.SelectedValue.ToString()
_CustNo = DropDownListCustomers.SelectedValue.ToString()
The records are being updated/inserted with those values. In more context:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PROSQL05;DATABASE=cpsdata;UID=sa;PWD=sqlsql"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Existing', EndDate = #DateTimeYesterday,
ChangedOn = #CurrentDateTime WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim insertDML As String = "INSERT INTO CustomerCategoryLog (MemberNo, Unit, Custno, Category, Subcategory,
BeginDate, ChangedBy, ChangedOn) VALUES (#MemberNo_Insert, #Unit_Insert, #CustNo_Insert, #Category, #Subcategory,
#BeginDate, #ChangedBy, #ChangedOn)"
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
_Unit = DropDownListUnits.SelectedItem.ToString()
_MemberNo = DropDownListMembers.SelectedValue.ToString()
_CustNo = DropDownListCustomers.SelectedValue.ToString()
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
cmd.Parameters.Add("#DateTimeYesterday", SqlDbType.DateTime).Value = DateTime.Today.AddDays(-1)
cmd.Parameters.Add("#CurrentDateTime", SqlDbType.DateTime).Value = Date.Now
conn.Open()
cmd.ExecuteScalar()
End Using
' Now insert a new record with "Existing" categories and Now as the BeginDate
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(insertDML, conn)
cmd.Parameters.Add("#MemberNo_Insert", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#Unit_Insert", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#CustNo_Insert", SqlDbType.VarChar, 50).Value = _CustNo
cmd.Parameters.Add("#Category", SqlDbType.VarChar, 50).Value = "Existing"
cmd.Parameters.Add("#Subcategory", SqlDbType.VarChar, 50).Value = "Existing"
cmd.Parameters.Add("#BeginDate", SqlDbType.DateTime).Value = DateTime.Today
cmd.Parameters.Add("#ChangedBy", SqlDbType.VarChar, 50).Value = Environment.UserName
cmd.Parameters.Add("#ChangedOn", SqlDbType.DateTime).Value = Date.Now
conn.Open()
cmd.ExecuteScalar()
End Using
End Sub
so, getting the displayed value like so:
_Unit = DropDownListUnits.SelectedItem.ToString()
...and the data values like so:
_MemberNo = DropDownListMembers.SelectedValue.ToString()
_CustNo = DropDownListCustomers.SelectedValue.ToString()
...does work.
I still (different question) cannot get the second and third dropdownlists to repopulate based on the value of the first one when it changes, though...
You need to fill DropDownListUnits only at initial page load by using If Not IsPostBack. Otherwise, DropDownListUnits is populated with new data on postback, and losts the selected value.
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
. . .
'Populate the Units dropdown
Dim unitsDT As DataTable
sql = "Select distinct unit from masterunits where abs(active) = 1"
retDS = sqlDAL.runSQLDataSet(sql)
unitsDT = retDS.Tables(0)
DropDownListUnits.DataSource = unitsDT
DropDownListUnits.DataTextField = "unit"
DropDownListUnits.DataValueField = "unit"
DropDownListUnits.DataBind()
. . .
End If
End Sub
Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
DropDownListMembers.Items.Clear
DropDownListCustomers.Items.Clear
Dim selectedUnit As String = DropDownListUnits.SelectedValue
^^^^^^
Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
Dim membersDT As DataTable
Dim retDS As DataSet
Dim sql As String = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
End Sub
i have created a code in asp.net webform
now i want this code to be run in console application
but i don't know
how to invoke my timer
and where to place the code
can someone help me to convert
these code into a console application
Dim con1 As New SqlConnection(_start)
Dim sql12 As String = "SELECT Auction.AuctionID FROM Item INNER JOIN Auction ON Item.ItemID = Auction.ItemID Where Auction.Status='Valid' AND Auction.EndDate<=#endate "
Dim cmd12 As New SqlCommand(sql12, con1)
con1.Open()
cmd12.Parameters.AddWithValue("#endate", DateTime.Now)
Dim query As Integer = cmd12.ExecuteScalar
Dim sql123 As String = "UPDATE Auction SET Status ='Expired' WHERE AuctionID =#auction"
Dim cmd21 As New SqlCommand(sql123, con1)
cmd21.Parameters.AddWithValue("#auction", query)
cmd21.ExecuteNonQuery()
CalculateWinningPrice(query)
WinningBet()
timer1.Enabled = True
Public Sub CalculateWinningPrice(ByVal query As Integer)
Dim price As Integer
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (AuctionID = #auction)"
Dim cmd1 As New SqlCommand(sql1, con1)
cmd1.Parameters.AddWithValue("#auction", query)
Dim max As Double = Convert.ToDouble(cmd1.ExecuteScalar)
Dim cmd2 As New SqlCommand("SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (BiddingPrice <( SELECT MAX(BiddingPrice) AS Expr2 FROM BID AS BID_1 WHERE (AuctionID = #auction)))", con1)
cmd2.Parameters.AddWithValue("#auction", query)
Dim second As Double = Convert.ToDouble(cmd2.ExecuteScalar)
Dim cmd3 As New SqlCommand("SELECT BuyerID FROM BID WHERE(BiddingPrice =(SELECT MAX(BiddingPrice) AS Expr1 FROM BID AS BID_1 WHERE(AuctionID = #auction)))", con1)
cmd3.Parameters.AddWithValue("#auction", query)
Dim Buyer As Integer = Convert.ToInt32(cmd3.ExecuteScalar)
If max - second = 1 Then
price = second
Else
If max - second > 10 Then
price = second + 1
Else
If max - second > 100 Then
price = second + 10
Else
If max - second > 1000 Then
price = second + 1000
End If
End If
End If
End If
Dim cmd As New SqlCommand("INSERT INTO BID VALUES(#Date, #BiddingPrice,#Status,#AuctionID,#BuyerID,#WinningPrice)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#BiddingPrice", max)
cmd.Parameters.AddWithValue("#Status", "Won")
cmd.Parameters.AddWithValue("#AuctionID", query)
cmd.Parameters.AddWithValue("#BuyerID", Buyer)
cmd.Parameters.AddWithValue("#WinningPrice", price)
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Using
End Sub
then calculate winning price
Private Sub WinningBet()
Dim Email As String
Dim auction1 As Integer = Convert.ToInt32(lblauction.Text)
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT TOP (1) Member.Email, BID.BidID FROM BID INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN Member ON Buyer.MemberID = Member.MemberID WHERE(Auction.AuctionID = #auction) and (BID.WinningPrice <>0) ORDER BY BID.BidID DESC"
Dim sqlcommand As New SqlCommand(sql1, con1)
sqlcommand.Parameters.AddWithValue("#auction", auction1)
Email = sqlcommand.ExecuteScalar()
End Using
Dim [to] As String = Email
Dim from As String = "virgoplaza11#gmail.com"
Dim password As String = ""
Dim subject As String = "BID"
Dim body As String = "Your bid has been Successfull Login to shoppingCart to Make Payment"
Dim email1 As New Thread(Sub() SendEmail1([to], from, password, subject, body))
email1.IsBackground = True
email1.Start()
End Sub
Private Sub SendEmail1(ByVal [to] As String, ByVal from As String, ByVal password As String, ByVal subject As String, ByVal body As String)
Using mm As New MailMessage(from, [to])
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential(from, password)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
End Using
End Sub
To use the Forms timer:
Add a reference to System.Windows.Forms
Imports System.Windows.Forms
For the Web.UI timer:
Add references to System.Web and System.Web.Extensions
Imports System.Web.UI
At module level declare the new timer:
Dim timer1 As New Timer
I have a masterpage that has this code in it:
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Session("userid") = Nothing Then
txtLoginUser.Visible = True
txtLoginPass.Visible = True
Else
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim useridComm As String = "SELECT name, surname FROM users WHERE user_id=#userid"
Dim sqlUserID As New SqlCommand
conn.Open()
Dim userid As String = Session("UserID")
sqlUserID = New SqlCommand(useridComm, conn)
sqlUserID.Parameters.AddWithValue("#userid", Convert.ToInt32(userid))
Dim datareader As SqlDataReader = sqlUserID.ExecuteReader()
datareader.Read()
If datareader.HasRows Then
userid = Session("UserID")
lblLoggedIn.Text = "[Welcome, " + datareader("name").ToString() & " " & datareader("surname").ToString() + " ]"
txtLoginUser.Visible = False
txtLoginPass.Visible = False
lblUsername.Visible = False
lblRegister.Visible = False
btnLogin.Visible = False
lblUsername0.Visible = False
End If
datareader.Close()
conn.Close()
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim loginSQL As New SqlCommand
Dim loginComm As String
Dim CommonFunctions As New CommonFunctions()
Dim dec_pass As String = CommonFunctions.EncryptPassword(txtLoginPass.Text.Trim)
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
loginComm = "SELECT user_id FROM users WHERE username=#username and password=#password"
conn.Open()
loginSQL = New SqlCommand(loginComm, conn)
loginSQL.Parameters.AddWithValue("#username", txtLoginUser.Text.ToString)
loginSQL.Parameters.AddWithValue("#password", dec_pass)
Dim dr As SqlDataReader = loginSQL.ExecuteReader()
dr.Read()
If dr.HasRows Then
Session("UserID") = dr("user_id")
ElseIf dr.HasRows = False Then
lblRegister.ForeColor = Drawing.Color.Red
lblRegister.Text = "Incorrect Username/Password."
End If
dr.Close()
conn.Close()
Response.Redirect("Default.aspx")
End Sub
</script>
On Button1 click the script should get the user_id by using the datareader and create a Session("UserID") and pass it to Default.aspx. Default.aspx then gets the Session("UserID") and searches for a user_id that has the same value and checks the roles using user_roles table, and if the role_id is 4 then tblAdmin is shown, otherwise, it isn't.
This is the code for Default.aspx:
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim UserID As Integer = Convert.ToInt32(Session("UserID"))
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim userTypeCommand As String = "SELECT role_id FROM users_role WHERE user_id=#UserID"
Dim userTypeSQL As New SqlCommand
conn.Open()
Try
userTypeSQL = New SqlCommand(userTypeCommand, conn)
userTypeSQL.Parameters.AddWithValue("#UserID", UserID)
Dim datareader As SqlDataReader = userTypeSQL.ExecuteReader
If datareader("role_id").ToString = "4" Then
tblAdmin.Enabled = True
tblAdmin.Visible = True
ElseIf datareader("role_id").ToString IsNot "4" Then
tblAdmin.Visible = False
End If
Catch ex As Exception
End Try
conn.Close()
End Sub
Protected Sub btnCreateArticle_Click(sender As Object, e As EventArgs) Handles btnCreateArticle.Click
Response.Redirect("addArticle.aspx")
End Sub
Protected Sub btnAdmin_Click(sender As Object, e As EventArgs) Handles btnAdmin.Click
Response.Redirect("Admin.aspx")
End Sub
End Class
When I debug, after I press the 'Login' button the user_id (Session('UserID') remains 0, when the user_id of the user I used to log with is '12' in the table.
What Am I doing wrong?
I am using ASP.NET/VB.NET and SQL Server 2012.
Fixed it. Had a missing datareader.Read().
I have a survey page, where i insert radio buttons dinamically in form load event. When i click the button to send the results, after postback, the radio buttons are still there, with the checked state correctly. But if i do some code, in the code behind, that tries to check if one of them is checked (by FindControl(id)), the page crashes. I canĀ“t do debug, so i don't know what error is.
<%# Control language="vb" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<%# Register TagPrefix="dnn" TagName="USER" Src="~/Admin/Skins/User.ascx" %>
<style>
body {background-image:none; background-color:transparent;}
</style>
<div style="float:left; width:420px; height:335px;" id="divPerguntas" enableviewstate="true" runat="server"></div>
<div style="float:left; width:420px; height:75px;"><asp:ImageButton ImageUrl="/Portals/_default/Skins/AdWin/img/Enviar.png" id="imgEnviar" runat="server" style="cursor:pointer;" /></div>
<div id="ContentPane" runat="server"></div>
<script runat="server">
Protected Sub EnviarClick() Handles imgEnviar.Click
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim checkedGroup As Boolean = False
Dim insertList As New DataTable
Dim ColumnIDSurveyOption As New DataColumn("c", GetType(Integer))
insertList.Columns.Add(ColumnIDSurveyOption)
Dim row As DataRow
For Each dr As DataRow In dt.Rows
If FirstQuestion Then
SurveyID = dr("SurveyID")
FirstQuestion = False
End If
If SurveyID <> dr("SurveyID") Then
SurveyID = dr("SurveyID")
checkedGroup = False
End If
If SurveyID = dr("SurveyID") And checkedGroup = False Then
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
If radiobuttonToCheck.Checked Then
checkedGroup = True
row = insertList.NewRow()
row("insertList") = dr("SurveyOptionID")
insertList.Rows.Add(row)
End If
End If
Next
If checkedGroup = True Then
Dim dnnUserCtrl As New DotNetNuke.Entities.Users.UserController
For Each dr As DataRow In insertList.Rows
sql = "INSERT INTO AdWin_Demo.dbo.Adwin_RespostasDadas (IDUser, SurveyOptionID) SELECT " & dnnUserCtrl.GetCurrentUserInfo.UserID & ", " & dr("SurveyOptionID").ToString()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
Next
Else
Response.Write("Nao respondeste a tudo")
End If
End If
myReader.Close()
conexao.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.EnableViewState = True
'If Not Page.IsPostBack Then
Dim conexao As SqlConnection
Dim comando As SqlCommand
Dim myReader As SqlDataReader
Dim sql As String
sql = "SELECT S.SurveyID, S.Question, SO.OptionName, SO.SurveyOptionID FROM AdWin_Demo.dbo.Surveys S INNER JOIN AdWin_Demo.dbo.SurveyOptions SO ON S.SurveyID = SO.SurveyID WHERE S.VideoId = " + Request.QueryString("id") + " ORDER BY S.ViewOrder, S.SurveyID, SO.ViewOrder"
conexao = New SqlConnection("#CONNECTIONSTRING#")
conexao.Open()
comando = New SqlCommand(sql, conexao)
myReader = comando.ExecuteReader
If myReader.HasRows Then
Dim dt As New DataTable
dt.Load(myReader)
Dim SurveyID As Integer = 0
Dim FirstQuestion As Boolean = True
Dim ActualDiv As System.Web.UI.HtmlControls.HtmlGenericControl
For Each dr As DataRow In dt.Rows
If SurveyID = dr("SurveyID") Then
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Else
SurveyID = dr("SurveyID")
If FirstQuestion = False Then
Dim hr2 As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr2)
End If
Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("DIV")
div.Style.Add("float", "left")
div.Style.Add("width", "400px")
div.Style.Add("color", "#777")
div.Style.Add("font-size", "11px")
div.Style.Add("line-height", "15px")
divPerguntas.Controls.Add(div)
ActualDiv = div
ActualDiv.InnerText = dr("Question").ToString()
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
Dim rb As New RadioButton
rb.GroupName = "Group" & SurveyID.ToString()
rb.ID = dr("SurveyOptionID").ToString()
rb.Text = dr("OptionName").ToString()
rb.EnableViewState = True
ActualDiv.Controls.Add(rb)
ActualDiv.Controls.Add(New LiteralControl("<br/>"))
FirstQuestion = False
End If
Next
Dim hr As New HtmlGenericControl("hr")
divPerguntas.Controls.Add(hr)
End If
myReader.Close()
conexao.Close()
End Sub
</script>
Try to add controls to the page in PreInit event and see if you can access data correctly. More details here http://msdn.microsoft.com/en-us/library/ms178472.aspx
Dim radiobuttonToCheck As RadioButton = FindControl(dr("SurveyOptionID").ToString())
->
Dim radiobuttonToCheck As RadioButton = Me.FindControl(dr("SurveyOptionID").ToString())
I am connecting to a database and then using an SQLDataReader to parse through those results and then put those results into variables that I can use at a latter time. The problem is that all of my "results.items" are returning null values. The DataReader is however, showing the proper field count when I debug.
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "editPost" Then
'Remove DataGrid'''''''''
GridView1.Visible = False
'''''''''''''''''''''''''
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = GridView1.Rows(index)
Dim ID As String = GridView1.Rows(index).Cells(0).Text
''''''''''''''''''''''''''''''''''''''''CREATE Controls for Placeholder
Dim editEditor As New CuteEditor.Editor
Dim hiddenID As New HiddenField
hiddenID.ID = "hiddenID"
hiddenID.Value = ID
editEditor.ID = "editEditor"
Dim subjectTXT As New TextBox
subjectTXT.ID = "editorSubject"
Dim br As New Literal
Dim submitChanges As New Button
Dim sbjLabel As New Label
submitChanges.ID = "submitChanges"
submitChanges.Text = " Submit Changes "
submitChanges.Height = 40
submitChanges.Width = 300
sbjLabel.Text = "Subject: "
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
editEditor.AutoConfigure = CuteEditor.AutoConfigure.Simple
br.Text = "<br/><br/>"
plcEditor.Controls.Add(hiddenID)
plcEditor.Controls.Add(sbjLabel)
plcEditor.Controls.Add(subjectTXT)
subjectTXT.Width = "100"
subjectTXT.Height = "25"
subjectTXT.CssClass = "editInput"
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(editEditor)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(submitChanges)
submitChanges.OnClientClick = UpdatePost()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim connStr As String = ConfigurationManager.ConnectionStrings("oakfratnewsConnectionString").ConnectionString
Dim nCon As New SqlConnection(connStr)
Dim addCon As New SqlConnection(connStr)
Dim addCom As New SqlCommand("SELECT * FROM [News] WHERE ([ID] = #ID)", addCon)
addCom.Parameters.AddWithValue("#ID", ID)
addCon.Open()
addCom.ExecuteNonQuery()
Dim results As SqlDataReader
results = addCom.ExecuteReader
While results.Read()
Dim editText As String = results.Item("Content")
Dim Subject As String = results.Item("Subject")
editEditor.Text = editText
subjectTXT.Text = Subject
End While
End If
End Sub
Where do you get the ID value?
"addCom.Parameters.AddWithValue("#ID", ID) "
Remove "addCom.ExecuteNonQuery() "
Why using
Dim editText As String = results.Item("Content")
I define before the loop the variable and then read it in this way
Dim editText As String
While results.Read()
editText = results("Content") ' without .items
...
End While