How do I Pass value from URL - vb.net

Morning,
Hi, I get stuck on how to parse a value as parameter from one page to another.
Here what I've already done
On Functional.aspx.vb, I parse value to Functional_Sub.aspx from URL
For Each row As DataRow In dt.Rows
html.Append("<a href='Functional_Sub.aspx?flag=" + row(0) + "'>IKUTI</a>")
Next
What I get is
'Functional_Sub.aspx?flag=FUNCP-000001' in URL
On Functional_Sub.aspx.vb I try to get parsed value with
Dim flag As String = Request.Params("flag")
Private Function GetData() As DataTable
Dim Connbackbone As String = ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString
Using con As New SqlConnection(Connbackbone)
Using cmd As New SqlCommand("SELECT a.[IDFuncChild], b.[IDFuncParent], a.[nmSubKat] FROM [EL_MstFunctional_SubKat] a inner join [EL_MstFunctional_Kat] b on b.[IDFuncParent] = a.[IDFuncParent] where IDFuncParent = #IDFuncParent order by b.IDFuncParent, a.IDFuncChild")
cmd.Parameters.AddWithValue("#IDFuncParent", flag)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
But I get this result
Request is not available in this context
Please guide me. Thanks

It should be after the page is generated.
Dim flag As String
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
flag = Request.Params("flag")
End Sub

Related

Converting Combobox Value.Member from Sttring to Integer?

I have 2 comboboxes which contain ID columns (SID & CID) as the valuemember and the displayMember is text.
I want to use the valueMembers to INSERT into an SQL database.
However the ValueMember property is a String and the column in the database is an Integer.
How can I get these 2 valueMembers converted into Integers.
The code for the complete form is shown below.
Imports System.Data.SqlClient
Imports My_Greeting.Add_VersesDataSetTableAdapters
Public Class frmAddRecord
Private MyDatAdp As New SqlDataAdapter
Private MyDataTbl As New DataTable
Private sql As String = Nothing
Private ds As New DataSet()
Private stepinfo As String = String.Empty
Dim E1 As String
Dim E2 As String
Dim Verse As String
Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
Private Sub frmAddRecord_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TopMost = True
Me.WindowState = FormWindowState.Normal
Me.Sub_EventTableAdapter1.Fill(Me.EventSubDataSet1.Sub_Event)
Me.Event_TypeTableAdapter1.Fill(Me.PrimEventDataSet1.Event_Type)
Dim evt As String
Dim SEvt As String
Dim Verse As String
Dim sql As String = Nothing
Dim ds As New DataSet()
Dim stepinfo As String = String.Empty
Try
stepinfo = "Step: instatiate connection"
Using connection As New SqlConnection(connectionString)
stepinfo = "step: test open connection"
connection.Open()
sql = "Select SID, EVENT from Event_Type"
Using adaptor As New SqlDataAdapter(sql, connection)
adaptor.Fill(ds, "Tab_Event_Type")
End Using
stepinfo = "Load second data"
sql = "Select BID,SUBEVENT from Sub_Event"
Using adaptor As New SqlDataAdapter(sql, connection)
adaptor.Fill(ds, "Tab_Sub_Event")
End Using
End Using
stepinfo = "Step: Bind Event combobox"
cboEvent.DataSource = ds.Tables("Tab_Event_Type")
cboEvent.ValueMember = "SID"
cboEvent.DisplayMember = "Event"
stepinfo = "Bind Sub_Event combobox"
cboSEvent.DataSource = ds.Tables("Tab_Sub_Event")
cboSEvent.ValueMember = "BID"
cboSEvent.DisplayMember = "SubEvent"
Catch ex As Exception
MessageBox.Show($"Error:{stepinfo}{vbNewLine}{ex.ToString}")
End Try
evt = cboEvent.ValueMember
SEvt = cboSEvent.ValueMember
Verse = txtNewVerse.Text
E1 = CType(evt, Integer)
E2 = CType(SEvt, Integer)
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim query As String = String.Empty
query &= "INSERT INTO Verse (Event, Event_Sub, Verse)"
query &= "VALUES (#Event, #Event_Sub, #Verse)"
Using conn As New SqlConnection("Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True")
Using Comm As New SqlCommand()
With Comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#Event", E1)
.Parameters.AddWithValue("#Event_Sub", E2)
.Parameters.AddWithValue("#Verse", Verse)
End With
Try
conn.Open()
Comm.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End Using
End Sub
End Class
I have tried CInt and CType, but they dont work.
Conversion from string "SID" to type 'Integer' is not valid.
The issue lies in these lines of code:
cboEvent.ValueMember = "SID"
...
Dim evt As String
...
evt = cboEvent.ValueMember
...
Dim E1 As String
...
E1 = CType(evt, Integer)
You can simplify it into
Dim E1 As String = CType("SID", Integer)
Which is obviously not going to work. I'm not sure of your intent, but this is surely your issue.
Edit to address your comments
Here is the title of your question Converting Combobox Value.Member from Sttring [sic] to Integer?
Let's try to figure out what you are trying to do. (By the way, it is nice when we don't need to try to figure out a questioner's intent; rather it is apparent. Anyway, let's do that now)
Regarding this nugget: Combobox Value.Member, it's unclear whether you actually want the ValueMember, SelectedValue, or Text (Text being the closest proxy to Value alone).
The ValueMember tells a control which property to return via SelectedValue when the control is data-bound. For example,
Dim source = (
From i In Enumerable.Range(5, 5)
Select New With {
.Number = i,
.Square = i ^ 2
}).ToList()
ComboBox1.DataSource = source
ComboBox2.DataSource = source
ComboBox2.DisplayMember = "Number"
ComboBox2.ValueMember = "Square"
Let's see what the results of the three properties in question are, for both ComboBoxes
MessageBox.Show($"{ComboBox1.ValueMember}, {ComboBox2.ValueMember}")
, Square
MessageBox.Show($"{ComboBox1.Text}, {ComboBox2.Text}")
{ Number = 5, Square = 25}, 5
MessageBox.Show($"{ComboBox1.SelectedValue}, {ComboBox2.SelectedValue}")
{ Number = 5, Square = 25}, 25
The last one is probably what you want. ComboBox2.ValueMember has been set as the "Square" property of the anonymous type in the LINQ expression.
So in your example, the offending code is in my first code block, and it should be obvious that assigning evt = cboEvent.ValueMember is wrong and that you probably wanted the SelectedValue
evt = cboEvent.SelectedValue
which should have been clear from our comments, and answer. #jmcilhinney's comment specifically
The ValueMember is the name of the member from which the values come. It is NOT the value(s). That's what the SelectedValue property is for. The SelectedValue is where you'll find the value from the specified member of the SelectedItem. – jmcilhinney 16 hours ago
that last part again
16 hours ago
You can lead a horse to water, but you can't make him drink.

Defining Variables that are accessible page wide

Good morning guys,
I am working on vb.net. The aim is to make a CodeFile run some sql queries and then return the values to the webpage as an sqldatasource query parameter on page load.
I have the following vb code
Partial Class Consult
Inherits Page
Public totalCount As Integer = "0"
'*******Here i declare the variable***************
Public Property PatNo() As String
Get
Return ViewState("PatNo")
End Get
Set(ByVal value As String)
ViewState("PatNo") = value
End Set
End Property
Public PatNam As String = "abc"
Public ConID As String = "abc"
Public TreatType As String = "abc"
Public HPC As Char = "abc"
Public LvTyp As RadioButtonList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Me.PatNo = Request.QueryString("pNo")
Session("PatientNo") = PatNo
Dim ConsultationID As String = Request.QueryString("consultID")
ConID = ConsultationID
Response.Write(PatNo)
Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Using con As New SqlConnection(constr)
'**********BELOW LINE CAUSES ERROR**************
Dim query As String = "SELECT * FROM hPatients WHERE pNO=#PatNo"
query += "SELECT * FROM hPatients WHERE pNO='001/000034824'"
Using cmd As New SqlCommand(query)
cmd.Parameters.Add("#PatNo", SqlDbType.NVarChar).Value = PatNo
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds)
gvPatientInfo.DataSource = ds.Tables(0)
'Return ds.Tables(0).Rows(0).Item(2)
'Response.Write(ds.Tables(0).Rows(0).Item(2))
gvPatientInfo.DataBind()
gvClientInfo.DataSource = ds.Tables(1)
gvClientInfo.DataBind()
End Using
End Using
End Using
End Using
If Not Me.IsPostBack Then
'Dim di As DataInfo = Me.GetInfo()
'Populating a DataTable from database.
Dim dt As DataTable = Me.GetData()
'Response.Write(ConID + " " + PatNo)
'Building an HTML string.
Dim html As New StringBuilder()
'Table start.
html.Append("<table border = '1' class = 'table'>")
'Building the Header row.
html.Append("<tr>")
For Each column As DataColumn In dt.Columns
html.Append("<th>")
html.Append(column.ColumnName)
html.Append("</th>")
Next
html.Append("</tr>")
'Building the Data rows.
For Each row As DataRow In dt.Rows
html.Append("<tr>")
For Each column As DataColumn In dt.Columns
html.Append("<td>")
html.Append(row(column.ColumnName))
html.Append("</td>")
Next
html.Append("</tr>")
Next
'Table end.
html.Append("</table>")
'Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(New Literal() With { _
.Text = html.ToString() _
})
End If
End Sub
The error i get is
Must declare the scalar variable "#PatNo".
The error occurs in the first step of getting the variable to execute the query in the page_load function.
The second step would be to get the result of the query and use on the webpage.
Somebody, Anybody, Please HELP!!!.
I think the problem is with this line:
cmd.Parameters.Add("PatNo", SqlDbType.NVarChar).Value = PatNo
Change the name from "PatNo" to "#PatNo" and it should work.

Delete Row / Remove Row

I want to delete my rows in gridview, but when I try many code the error are same.
When I try this
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "xyz"
cmd.Connection = sqlCon
sqlCon.Open()
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
sqlCon.Close()
If Gridview1.Rows.Count = 0 Then
Dim dtempty As DataTable = Nothing
dtempty = (DirectCast(Gridview1.DataSource, DataTable)).Clone()
dtempty.Rows.Add(dtempty.NewRow())
Gridview1.DataSource = dtempty
Gridview1.DataBind()
Gridview1.Rows(0).Visible = False
'Gridview1.Rows(0).Controls.Clear()
Else
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("rupiah") = PyrDLL.Decrypt(dt.Rows(i)("rupiah"))
dt.Rows(i)("rupiah") = Decimal.Parse(dt.Rows(i)("rupiah")).ToString()
'i = i + 1
Next
Gridview1.DataBind()
For i As Integer = Gridview1.Rows.Count - 1 To 1 Step -1
Dim row As GridViewRow = Gridview1.Rows(i)
Dim prevrow As GridViewRow = Gridview1.Rows(i - 1)
If (TryCast(Gridview1.Rows(i).Cells(1).FindControl("lblketerangan"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(1).FindControl("lblketerangan"), Label).Text.ToString()) And (TryCast(Gridview1.Rows(i).Cells(0).FindControl("lblcomp"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(0).FindControl("lblcomp"), Label).Text.ToString()) Then
Dim total As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total2 As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total3 As Decimal
total3 = total + total2
DirectCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text = Decimal.Parse(total3).ToString()
row.Visible = False
'Gridview1.Rows.Remove(Gridview1.Rows(i)) <--- if i comment here its run without problem
End If
Next
End If
End Using
End Using
the error
Remove' is not a member of 'System.Web.UI.WebControls.GridViewRowCollection'
Can you help me?
now, i hide the row after i sum it but i want to auto delete / remove row after i sum it not only hide
Thanks
I am not sure what you are trying to do when there are no rows, the gridview would be empty
You should do the following instead:
'Call GetData() every time you want to bind data to the gridview
Private Function GetData()
Gridview1.DataSource = Nothing
Gridview1.DataBind()
Dim strQuery = "SELECT..."
Dim dt As New DataTable()
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand(strQuery, sqlCon)
'Add cmd parameters as required to prevent SqlInjection
sqlCon.Open()
Using ada As New SqlDataAdapter(cmd)
ada.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
End Using
End Using
End Using
End Function
When handling the data in the gridview you can use RowDataBound, you could then call a separate function to handle deleting a row after your logic is handled where the criteria is met to delete a row
Protected Sub Gridview1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Handle databound logic
End If
End Sub
You should be able to tailor this to your needs, just called GetData() everytime you need to rebind data to the gridview
I solved my problem
i cant remove rows from data gridview but i remove data from data table and bind it after thats
thanks everyone

Database record not updated

Hi everyone I'm new to here, I have problem to update my database record in VB ASP.NET webform. My code below will return dialog box that says record updated successfully when cmd.ExecuteNonQuery() > 0 but the record in database not being updated in fact. Sorry for my bad english. Please help thanks in advance.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim staffUsername As String = Session("StaffUsername").ToString()
Dim staffFNm As String = txtStaffFNm.Text
Dim staffLNm As String = txtStaffLNm.Text
Dim staffEmail As String = txtStaffCpnyEmail1.Text + txtStaffCpnyEmail2.Text
Dim staffBDay As String = txtBirthday.Text
Dim staffPhone As String = txtPhoneNo.Text
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("SupportSystemDB").ConnectionString)
con.Open()
Dim myCommand As New SqlCommand("UPDATE STAFF SET StaffFNm = #staffFNm, StaffLNm = #staffLNm, StaffEmail = #staffEmail, StaffBirthday = #staffBDay, StaffPhone = #staffPhone WHERE StaffUsernm = #staffUsernm", con)
myCommand.Parameters.AddWithValue("#staffFNm", staffFNm)
myCommand.Parameters.AddWithValue("#staffLNm", staffLNm)
myCommand.Parameters.AddWithValue("#staffEmail", staffEmail)
myCommand.Parameters.AddWithValue("#staffBDay", staffBDay)
myCommand.Parameters.AddWithValue("#staffPhone", staffPhone)
myCommand.Parameters.AddWithValue("#staffUsernm", staffUsername)
If myCommand.ExecuteNonQuery() > 0 Then
Response.Write("<script>alert('Your Account Info Has Been Successfully Updated.');</script>")
con.Close()
Else
Response.Write("<script>alert('Record Update Failed.');</script>")
End If
End Using
End Sub

Combobox selected Item does not match with its selected

I faced with that issue which appears with spaces after letters finished more than Combobox.SelectedItem's length. Why? How can I fix this issue?
Below is showing my issue as visual its a very short and small video.
Here is a small video
Imports System.Data.SqlClient
Public Class Main
WithEvents bsData As New BindingSource
Dim sConn As New SqlConnection
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sConn.ConnectionString = "Data Source=PC-N39;Initial Catalog=Esi01;Persist Security Info=True;User ID=sa;Password=sas"
sConn.Open()
Try
Dim myTable As DataTable = New DataTable("MyTable")
myTable.Columns.Add(New DataColumn("Group Code"))
myTable.Columns.Add(New DataColumn("Description"))
myTable.Columns.Add(New DataColumn("NothingSerious"))
Dim cmd As New SqlCommand("Select * from tbUnit", sConn)
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.Default)
Dim myRow As DataRow
While dr.Read()
myRow = myTable.NewRow
myRow.Item(0) = dr(0)
myRow.Item(1) = dr(1)
myRow.Item(2) = dr(2)
myTable.Rows.Add(myRow)
End While
dr.Close()
Dim myData4 As DataTable = myTable
ds = New DataSet()
ds.Tables.Add(myData4)
MultiColumnCombo1.DisplayMember = "Group Code"
MultiColumnCombo1.DrawMode = DrawMode.OwnerDrawVariable
MultiColumnCombo1.ColumnWidths = "50;150"
MultiColumnCombo1.DataSource = myData4
MultiColumnCombo1.Text = String.Empty
Catch ex As Exception
MsgBox(ex.ToString)
End Try
sConn.Close()
End Sub
End Class
What type is MultiColumnCombo1 ? I suppose it's a third party component.
As far as I can see in your video, it seems that it takes the biggest element in your data, take it's length and add spaces to other elements to make them the same size.
You probably won't be able to change the component's behavior, but you can apply the same logic to what you enter in your TextBox : adding spaces to make them match. Or if you simply need to make a condition that test if they are equal, you can do as follow :
if(YourComboboxSelectedItem.Trim() == StringYourAreComparingItTo)
See String.Trim(), that will discard the extra whitespaces.