Binding Url to Gridview - asp.net

I want to bind the url to GridView but I don't know how.
For example when I type the http://localhost:12345/example.aspx?FirstName=John in the url it will give me the result in GridView that shows only with the FirstName "John".
Here's my curent code:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim dt As New DataTable
' Stablish ODBC Connection
Dim con As New OdbcConnection("DRIVER={SQL Server};Server=WJNJPHR8TCX8P\SQLEXPRESS;Database=Fabrics;Integrated Security=True;")
' Query Command
Dim cmd As New OdbcCommand("SELECT * FROM [Client] WHERE [FirstName] = ?", con)
con.Open()
' Gets the path (Example.aspx)
Dim path As String = HttpContext.Current.Request.Url.AbsolutePath
' Gets the host (localhost)
Dim host As String = HttpContext.Current.Request.Url.Host
' Gets the whole url (localhost:24124/Example.aspx)
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
' Parse the query string variables into a NameValueCollection
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(url)
' Iterate through the collection and shows the result in MsgBox
Dim sb As New StringBuilder()
For Each s As String In qscoll.AllKeys
sb.Append(s & " = " & qscoll(s) & vbCrLf)
Next s
MsgBox(sb.ToString)
' Gets all keys and values in query string and shows it on MsgBox
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
Next key
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter
par1.OdbcType = OdbcType.NVarChar
par1.Value = FName
par1.ParameterName = "#FirtName"
cmd.Parameters.Add(par1)
'Shows the result in Data Grid
dt.Load(cmd.ExecuteReader()) '==> Error: Invalid use of default parameter
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Any help will do!

You can access your query string directly with
Dim firstName as string = Request.QueryString("firstName")
Then you must pass it as a parameter of the query before executing it
Dim par1 As New OdbcParameter
par1.DbType = DbType.String
par1.Value = firstName
par1.ParameterName = "#FirstName"
cmd.Parameters(1) = par1
Hope it helps

Answered my question!
Here's my code:
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter With {
.OdbcType = OdbcType.NVarChar,
.Value = FName,
.ParameterName = "#FirstName"
}
cmd.Parameters.Add(par1)
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView1.DataBind()
Next key
#isol Thanks for your help! :)

Related

Make a for each using SqlDataReader vb.net

i need store the value "IdMaterial" from table 1 ( imagine that have more that 40 records) into a array save all that reacord into table 2 on the code i will show you only save me the first record and not all.
i will apreceate your help i a noobie in proraming
Code :
Dim i As Integer
i = 0
Try
Dim mater As String
Dim planta As String
Dim almacen As String
Dim lot As String
Dim cantidad As String
Dim cantadiat As String
Dim undad As String
Dim Cantidadc As String
Dim CantidadB As String
Dim Session1 As String
Dim fecha As String
'''''
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Using CustCommand As New SqlCommand(editCustQuery, Con34)
Dim dr As SqlDataReader = CustCommand.ExecuteReader()
dr.Read()
mater = dr.GetString(0)
planta = dr.GetString(1)
almacen = dr.GetString(2)
lot = dr.GetString(3)
cantidad = dr.GetString(4)
cantadiat = dr.GetString(5)
undad = dr.GetString(6)
Cantidadc = dr.GetString(7)
CantidadB = dr.GetString(8)
Session1 = dr.GetString(9)
fecha = dr.GetDateTime(10)
end using
Dim Con As New Data.SqlClient.SqlConnection
Dim StrSQL As String
Con.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL = ""
StrSQL = "EXEC P_AsigDupla '" & Txtfecha.Text & "','" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "','" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater & "', '" & lot & "'"
Con.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL, Con)
CmdAd.ExecuteNonQuery()
Con.Close()
i = i + 1
'Next
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
First of all if I understand correctly, you want to put the information of those 40 rows and multiple columns into multiple arrays. If that is true then you are missing () when declaring the arrays.
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim RowCounter as Integer = 0
Second I will approach this different. I will run the query and put the result into a DataTable. Then with a For go through each row and start filling the arrays.
MySQLOpenConnection()
Dim MySQLExecute As New MySqlCommand(MySQLCommand, MySQLConnection)
Dim MySQLAdapter As MySqlDataAdapter = New MySqlDataAdapter(MySQLExecute)
Dim TableResult As New DataTable("QueryResult")
MySQLAdapter.Fill(TableResult)
MySQLCloseConnection()
For each tablerow as DataRow in TableResult.Rows
mater(RowCounter) = TableResult.Rows.Item(RowCounter).Item(0)
planta(RowCounter) = TableResult.Rows.Item(RowCounter).Item(1)
almacen(RowCounter) = TableResult.Rows.Item(RowCounter).Item(2)
lot(RowCounter) = TableResult.Rows.Item(RowCounter).Item(3)
cantidad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(4)
cantadiat(RowCounter) = TableResult.Rows.Item(RowCounter).Item(5)
undad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(6)
Cantidadc(RowCounter) = TableResult.Rows.Item(RowCounter).Item(7)
CantidadB(RowCounter) = TableResult.Rows.Item(RowCounter).Item(8)
Session1(RowCounter) = TableResult.Rows.Item(RowCounter).Item(9)
fecha(RowCounter) = TableResult.Rows.Item(RowCounter).Item(10)
RowCounter=RowCounter+1
Next
The comment did not have enough characters for the answer for the second issue so here it goes.
Ok, I see you are using values from the array mater, and lot, but you have to define which one of the values inside the array.
mater() and lot() are as long as the amount of rows of the of the table in the database. So if you have 20 rows on that table, the array lot will have 20 elements going from lot(0) to lot(19) and the same for the others.
If you need to get resultado for each row, then you have to define resultado() as an array and use the same FOR to fill it.
resultado(RowCounter)=GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter)
I hope this solve your issue.

Result set is not displaying in GridView

When I type the information in the TextBox there is no result in the GridView only the URL Parameter appear.
For example.
FNameTextBox.Text = "Mark"
The result is nothing just the URL says that
http://localhost:65319/Example.aspx?FirstName=Mark
In the GridView there is no result.
This is my current code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim dt As New DataTable
Using con As New OdbcConnection("DRIVER={SQL Server};Server=WJNJPHR8TCX8P\SQLEXPRESS;Database=Fabrics;Integrated Security=True;"),
cmd As New OdbcCommand("SELECT * FROM [Client] WHERE [ClientId] = ? OR [FirstName] = ? OR [MiddleName] = ? OR [LastName] = ?", con)
con.Open()
If IsNumeric(idTextBox.Text) Then
cmd.Parameters.Add("#ClientId", OdbcType.Int).Value = Integer.Parse(idTextBox.Text)
Response.Redirect("Example.aspx?ClientId=" + idTextBox.Text)
Else
cmd.Parameters.Add("#ClientId", OdbcType.Int).Value = -1
End If
cmd.Parameters.Add("#FirstName", OdbcType.NVarChar).Value = FNameTextBox.Text
Response.Redirect("Example.aspx?FirstName=" + FNameTextBox.Text)
cmd.Parameters.Add("#MiddleName", OdbcType.NVarChar).Value = MNameTextBox.Text
Response.Redirect("Example.aspx?MiddleName=" + MNameTextBox.Text)
cmd.Parameters.Add("#LastName", OdbcType.NVarChar).Value = LNameTextBox.Text
Response.Redirect("Example.aspx?LastName=" + LNameTextBox.Text)
dt.Load(cmd.ExecuteReader())
End Using
GridView1.DataSourceID = Nothing
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Question:
How can I display the Result set in GridView?
Why using Response.Redirect? comment all of them and your code is working.
If you want to send first name, middle name, last name as a query string, you should firstly store all the values then redirect to another page, or send all the textbox values in single query string.
String fname = fNameTextBox.Text
String mname = mNameTextBox.Text
String lname = lNameTextBox.Text
Response.Redirect("Example.aspx?FirstName="+fname+"&MName="+mname+"&LastName=" + lname)
or
Response.Redirect("Example.aspx?FirstName="+fNameTextBox.text+"&MName="+mNameTextBox.text+"&LastName=" + lNameTextBox.text)

Using ViewState to apply filters on Listview

I have used ListView Control to gets list of products from database. I also stores result in viewstate . Now to apply filter from checkbox to get refined data I want to know how can I use viewState values?
e.g. If 10 Products found in Music category when page loads. Now if user apply filter(Bluetooth) then only that products should be shown which are in Music & has bluetooth..
Now It is working Like on page load Music category gets fetched Then if I check Bluetooth filter then all bluetooth products comes which are not related to music.
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim pageName As String = Me.Page.RouteData.Values("category").ToString()
if not Me.isPostback Then
Try
query = select * from products where category = '"+pageName+"'
Dim conString As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim con As New MySqlConnection(conString)
Dim cmd As New MySqlCommand(query)
con.Open()
Dim da As New MySqlDataAdapter()
cmd.Connection = con
da.SelectCommand = cmd
Dim dt As New DataTable()
da.Fill(dt)
ViewState("Data") = dt
products.DataSource = dt
products.DataBind()
catHeading.Text = pageName
itemCount.Text = dt.Rows.Count.ToString
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
Filter Apply code
Private Sub priceFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles priceFilter.SelectedIndexChanged
'buildWhereClause()
Dim price As String = priceFilter.SelectedValue.ToString()
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.[Select]((Convert.ToString("category='") & price) + "'")
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Sub
I just want when user apply any filter then it should check from viewstate(Data) rather to entire table.
Save your category in viewstate & on Checked get that category in string & join that string in your query. something like this
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim query As String = "select * from table"
Dim joiner As String = ""
Dim condition As String = String.Empty
Dim whereClause As String = String.Empty
Dim priceCondition As String = String.Empty
Try
Dim category As String = ViewState("Data")
condition = String.Concat(condition, joiner, String.Format("{0}", category))
If joiner = "" Then joiner = ""
joiner = " where "
If Not String.IsNullOrEmpty(condition) Then
whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", condition))
joiner = " and "
End If
'Same way you can apply multiple filters as you want & then get that in one string like below
Dim masterClause As String = String.Empty
masterClause = (query & whereClause)
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(masterClause)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Using
End Using
End Using
End Using
For your filter you could use :
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.Select("category='" & category & "'")
products.DataSource = dr
products.DataBind()
itemCount.Text = dr.Length

ASP.NET variable not getting assigned values

Im having problem with this asp.net code.
the variables qty and itname are not getting valid values ...can anyone find out the problem ?
Imports System.Data
Imports System.Data.SqlClient
Partial Class consolidate
Inherits System.Web.UI.Page
Public lastreq_no As Int32
Protected Sub btnconsolidate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnconsolidate.Click
Dim qtypen As Integer
Dim qtypencil As Integer
Dim qtygbag As Integer
Dim qtysugar As Integer
Dim i As Integer
Dim req As Integer
Dim qty As Integer
Dim itname As String = ""
Dim sqlcon As New SqlConnection("Data Source=user-hp\sqlexpress;initial catalog=campco;integrated security=true;")
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim str As String
str = "Select Req_no from Requirements "
Dim cmd As New SqlCommand(str, sqlcon)
Dim sdr As SqlDataReader
sdr = cmd.ExecuteReader()
sdr.Read()
lastreq_no = sdr.GetInt32(sdr.VisibleFieldCount - 1)
For i = 0 To sdr.VisibleFieldCount - 1
req = sdr.GetInt32(i)
While req > lastreq_no
Dim selcomnd1 As String
Dim selcomnd2 As String
selcomnd1 = "Select #itname=It_name from Requirements where Req_no= #req"
selcomnd2 = "Select #qty= Quantity from Requirements where Req_no= #req"
Dim sqlcomnd1 As New SqlCommand(selcomnd1, sqlcon)
Dim sqlcomnd2 As New SqlCommand(selcomnd2, sqlcon)
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
sqlcomnd2.Parameters.AddWithValue("#qty", qty)
sqlcomnd1.ExecuteScalar()
sqlcomnd2.ExecuteScalar()
TextBox1.Text = itname
TextBox2.Text = qty
sqlcon.Close()
sqlcon.Open()
Select Case (itname)
Case "Pen"
qtypen += qty
lastreq_no = req
Case "Pencil"
qtypencil += qty
lastreq_no = req
Case "Gunny bag"
qtygbag += qty
lastreq_no = req
Case "Sugar"
qtysugar += qty
lastreq_no = req
End Select
End While
Next
sqlcon.Close()
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim comm As String
comm = "Insert into Consolidate (lastr_no,qtypen,qtypencil,qtygunnybag,qtysugar)values('" + lastreq_no.ToString + "','" + qtypen.ToString + "','" + qtypencil.ToString + "','" + qtygbag.ToString + "','" + qtysugar.ToString + "')"
Dim sqlcomm As New SqlCommand(comm, sqlcon)
Dim s As String
s = sqlcomm.ExecuteNonQuery()
sqlcon.Close()
End Sub
End Class
To start with, neither scalar statement is valid. Have you attempted to run those statements in SQL Management Studio or similar program to test the statements themselves? They should be something like:
selcomnd1 = "Select It_name from Requirements where Req_no=#req"
selcomnd2 = "Select Quantity from Requirements where Req_no=#req"
And then you would assign them in this manner:
itname = CType(sqlcmnd1.ExecuteScalar(), String) ' .ToString() would probably work here as well
qty = Convert.Int32(sqlcmnd2.ExecuteScalar())
Or you could use .TryParse for the qty:
Integer.TryParse(sqlcmnd2.ExecuteScalar(), qty)
The line
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
provides an input parameter with the value itname. No value has been assigned to this variable.
You need to add an output parameter: see here for how to do this.
Get output parameter value in ADO.NET

(ASP.NET) SQL Data Reader returning Null Values

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

Resources