How to execute a dynamic stored procedure that return a table in vb6 recordset and assign Datasource to a spreadgrid - stored-procedures

I wrote a dynamic procedure than populate the columns and then use Pivot to show the data.
How to execute this procedure from vb6 and return the content as datasource.

You can use ADO for this, you will need to add a reference to Microsoft ActiveX Data Ojects. The code as I remember (long time since vb6) is something like
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim strConn As String
Dim strSQL As String
Dim strCol1 As String
Dim strCol2 As String
strConn = "[YOUR CONNECTION SRING]" '(see www.connectionstrings.com for help)
conn.Open connStr
strSQL = "[YOUR SQL QUERY]" '(IE. Proc name)
rs.Open strSQL, conn, adOpenStatic, adLockOptimistic
Do While Not rs.EOF
strCol1 = rs.Fields("Col1Name")
strCol1 = rs.Fields("Col2Name")
rs.MoveNext
Loop
If rs.State = adStateOpen Then rs.Close
Set rs = Nothing
If conn.State = adStateOpen Then conn.Close
Set conn = Nothing

Related

Padright in combo box displaymember

I have the following 2 segments of code which populates my combo box but the First Name column obviously is a squiggly one since surnames are various lengths. How could I use something like padright to align the first name column? I have other code using a binding source method but it seems a bit long winded & I'd like to improve on that for all the combos I still have to create.
If RadioButton1.Checked Then
strSQL = "select *, Surname + ' ' + First_Name as Name from tblCompetitors order by Surname, First_Name"
cboData()
End If
Public Sub cboData()
Dim dt As New DataTable
Using conn As New SqlClient.SqlConnection(connString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Using com As SqlCommand = New SqlCommand(strSQL, conn)
Dim dr As SqlDataReader = com.ExecuteReader()
'Dim dt As DataTable = New DataTable
dt.Load(dr)
' as an example set the ValueMember and DisplayMember'
cboFindCompetitor.ValueMember = "Competitor_Idx"
cboFindCompetitor.DisplayMember = "Name"
'Set combobox’s datasource to datatable dt
cboFindCompetitor.DataSource = dt
End Using 'com
End Using 'conn
cboFindCompetitor.SelectedIndex = -1
End Sub
After some fiddling I came up with this solution. It works well on my machine with +- 3000 records in the table
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
If RadioButton1.Checked Then
strSQL = "select Competitor_Idx, Surname as Value1, First_Name as Value2 from tblCompetitors order by Value1, Value2"
cboData(25)
End If
End Sub
Public Sub cboData(z As Integer)
Dim dt As New DataTable
Using conn As New SqlClient.SqlConnection(connString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Using com As SqlCommand = New SqlCommand(strSQL, conn)
Dim dr As SqlDataReader = com.ExecuteReader()
'Dim dt As DataTable = New DataTable
dt.Load(dr)
dt.Columns.Add("Name", GetType(String))
' as an example set the ValueMember and DisplayMember'
cboFindCompetitor.ValueMember = "Competitor_Idx"
cboFindCompetitor.DisplayMember = "Name"
For Each row In dt.Rows
row.item("Name") = row.item("Value1").padright(z) + row.item("Value2")
Next
'Set combobox’s datasource to datatable dt
cboFindCompetitor.DataSource = dt
End Using 'com
End Using 'conn
cboFindCompetitor.SelectedIndex = -1

vb.net OLEDB Parametarize query

When i put parameter in my OLEDB code it compile successfully but it doesn't do the task. For example this delete data code:
Try
If dbconn.State = ConnectionState.Closed Then
dbconn.Open()
End
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = "DELETE FROM UsersTB WHERE First_Name =?"
dbCommand.Connection = dbconn
dbCommand.Parameters.AddWithValue("#row", 0)
Dim rows = dgvusers.SelectedRows
For Each row In rows
dbCommand.Parameters("#row").Value = row.Cells("First_Name").Value
dbCommand.Connection = dbconn
dbCommand.ExecuteNonQuery()
Next
MsgBox("Deleted")
Catch ex As Exception
ex.ToString()
End Try
This code is written on button when i compiled and click the button it doesn't delete the data i tried putting it on try catch and putting msgbox to indicate if the command is successful it and it indicate its "Deleted" but it doesn't work.

Getting a value from one table to pull up values from another table

I am trying to lookup an employeeid from one table based on the windows login name, and use this employeeid to get values from another table to add them up. So, for Bill, the employeeid is 1 in tblEmployees. I sum all noofhours in tblTimeAvailable where employeeid equals 1 and display this on my webpage. It's not working. I can't figure out how to search the second table by the employeeid found in the first table. (I'm rewriting code because of sql injection.)
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
con.Open()
rve = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
End Using
When I look at value of rve, it's giving me #loginname and not the employeeid. FYI - there will always be only one row in tblEmployees because each Windows login name is unique.
'Get Sick Time
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #employeeid"
Dim command As New SqlCommand(sqls1, con)
con.Open()
rvsa = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#employeeid", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
End Using
' If the sum equals 0, show 0 on webpage. If another value, show value.
If IsDBNull(rvsa) Then
rvsa = 0
TextBoxsa.Text = 0
Else
TextBoxsa.Text = rvsa.ToString
End If
I appreciate any help you can give me!
You are never executing the command. After setting the values of the various parameters, you need to then call one of the execute methods on the SqlCommand object. In this case, since you are just reading a single value from a single row, you can simply use the ExecuteScalar method:
rve = command.ExecuteScalar()

Visual Foxpro Database Stored Procedure with Oledb Provider

I am using Visual Foxpro 8.0 database. Below procedure I am using to return records from database on basis of condition matching but it raised error that:
"Function is not implemented."
Foxpro Procedure ------------------------
PROCEDURE FX_Proc_ValidateUser (paramUserName AS Character, paramPassword AS Character)
LOCAL VarUserName AS Character, varXml
VarUserName = IIF(VARTYPE(paramUserName)!="N","",paramUserName)
LOCAL VarPassword AS Character
VarPassword = IIF(VARTYPE(paramPassword)!="N","",paramPassword)
SELECT userinfoid, ;
username, ;
password ;
FROM tm_userinfo.dbf ;
WHERE username = VarUserName AND password = VarPassword ;
INTO CURSOR procResult
varXml = ""
CURSORTOXML("procResult","varXml",1,32,0,"1")
RETURN varXml
ENDPROC
Front End code for calling this procedure------------------
string ConnectionString = "Provider=VFPOLEDB.1;Data Source=C:\Users\raj\Documents\Visual FoxPro Projects\dbFoxMaster.dbc;Collating Sequence=machine;" providerName="System.Data.OleDb.OleDbConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
OledbConnection objOleDbConnection = new OleDbConnection(ConnectionString);
objOleDbConnection.Open();
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.CommandType = CommandType.StoredProcedure;
objOleDbCommand.CommandText = "FX_Proc_ValidateUser";
objOleDbCommand.Connection = objOleDbConnection;
objOleDbCommand.Parameters.Add("paramUserName", OleDbType.Char).Value = "abc";
objOleDbCommand.Parameters.Add("paramPassword", OleDbType.Char).Value = "123";
var xmlString = oOleDbCommand.ExecuteScalar().ToString();
DataTable table = new DataTable();
using (var reader = new StringReader(xmlString))
{
var dataSet = new DataSet();
// creating a dataset from the xml
dataSet.ReadXml(reader);
table = dataSet.Tables[0];
}
How to get resultset from foxpro 8.0 stored procedure using OledbCommand?
It looks like the problem is that you are putting your results into an array and only the first item in the array is being returned. You should change the stored procedure so that it uses a cursor.
VFP9 Example
Here is a stored procedure example from the northwind.dbc:
Here is an example of calling the stored procedure using C#:
var northwindDbcPath = #"C:\Program Files (x86)\Microsoft Visual FoxPro 9\Samples\Northwind\Northwind.dbc";
var connectionString = "Provider=VFPOLEDB.1;Data Source=" + northwindDbcPath;
var table = new DataTable();
using(var connection = new OleDbConnection(connectionString)) {
using(var command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CustOrdersDetail";
command.Parameters.Add("x", 10248);
var adapter = new OleDbDataAdapter(command);
adapter.Fill(table);
}
}
VFP8 Example:
(I don't have a copy of VFP8 but I believe that this will work)
var northwindDbcPath = #"C:\Program Files (x86)\Microsoft Visual FoxPro 9\Samples\Northwind\Northwind.dbc";
var connectionString = "Provider=VFPOLEDB.1;Data Source=" + northwindDbcPath;
DataTable table;
using(var connection = new OleDbConnection(connectionString)) {
using(var command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CustOrdersDetail2";
command.Parameters.AddWithValue("x", 10248);
connection.Open();
// executing stored procedure and getting xml result
var xml = command.ExecuteScalar() as string;
connection.Close();
using(var reader = new StringReader(xml)) {
var dataSet = new DataSet();
// creating a dataset from the xml
dataSet.ReadXml(reader);
table = dataSet.Tables[0];
}
}
}
I have no VFP around and the last time I used VFP it was still version 3.0...
I would try something like this based on the specs here. To learn the rest read-up here
PROCEDURE insertData (pusername, ppassword)
SELECT userinfoid, username, password
FROM tm_userinfo.dbf
WHERE username = pusername AND password = ppassword
INTO ARRAY results
RETURN results
ENDPROC
A Visual Foxpro stored procedure is basically using Visual Foxpro code to perform tasks such as validating columns on insert or update or delete.
For Example, you might add the following code to VFP database stored procedure to validate a "State" column:
PROCEDURE ValidateState()
IF address.state <> [OH]
MESSAGEBOX([Incorrect State value!], 48, [Invalid State])
ENDIF
ENDPROC
For querying a table in a Foxpro database, you may want to look at creating local views. You can do this by right clicking inside the foxpro database and selecting "New Local View", then define your view using the query builder. In the Filter tab, under the "Example" column, you can define parameters using the "?" such as "?pusername".
Here is how you would call the view from your Foxpro code:
LOCAL pusername AS Integer
pusername = "SomeUserName" &&Use this to filter the view
SELECT 0
USE MyViewName &&This will call the view and perform the filter.
You can also make these views updatable and perform your inserts against the view.

Drop-down list not populating other controls

I am a complete newb to webapps but here goes.
I have web form with a drop-down list that populates a list of holiday resorts from a database procedure. That bit works fine. When I select an item from the list I need to populate a listbox with hotels specific to that resort.
This bit I am having trouble with, the list does populate if I click off the drop-down list onto a calendar control on the form.
Question: how do I get it to populate the list after I clcik on the value from the drop-down list?
Thanks
Here is the code by the way:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
Me.Calendar1.SelectedDate = Now()
Me.DropDownList1.Items.Clear()
Dim connStr As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlClient.SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "<<sql_string>>"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
DropDownList1.DataTextField = "Rcode"
DropDownList1.DataValueField = "Rcode"
DropDownList1.DataSource = ds.Tables("Products")
DropDownList1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Me.ListBox1.Items.Clear()
Me.ListBox2.Items.Clear()
Dim connStr As String = WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "sql_string '" & Me.DropDownList1.Text & "'"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
ListBox1.DataTextField = "accommDescription"
ListBox1.DataValueField = "accommCode"
ListBox1.DataSource = ds.Tables("Products")
ListBox1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
ListBox1.Focus()
End Sub

Resources