I have a DataGridView in a page. When configure the DataSource (with sql or Access), update work perfectly. But if I put a Combo for filter data, in Page_Load I modify the SelectCommand and do a DataBind() to update the GridView. That's right. Click in Edit and modify some field, and when do click in Update, no modify the data in table.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load<br>
If RadioButtonList1.SelectedValue = "Todos" Then
AccessDataSource1.SelectCommand = "SELECT `revisado`, `aprobado`, `Id`, `fecha`, `hora`, `empresa`, `tipo`, `legajo`, `desde`, `hasta`, `pasajero1`, `pasajero2`, `pasajero3`, `ccosto1`, `ccosto2`, `ccosto3`, `valor`, `indiv1`, `indiv2`, `indiv3`, `peaje`, `regreso`, `espera`, `czona`, `recorrido`, `total`, `obs`, `comprobante`, `exportado` FROM `viajes` WHERE `exportado`=False"
DropDownList1.Visible = False
DropDownList2.Visible = False
Label1.Visible = False
ElseIf RadioButtonList1.SelectedValue = "Choferes" Then<br>
DropDownList1.Visible = True<br>
DropDownList2.Visible = False<br>
Label1.Visible = True<br>
Label1.Text = "Seleccione un Chofer"<br>
If DropDownList1.SelectedValue = Nothing Then<br>
AccessDataSource1.SelectCommand = "SELECT `revisado`, `aprobado`, `Id`, `fecha`, `hora`, `empresa`, `tipo`, `legajo`, `desde`, `hasta`, `pasajero1`, `pasajero2`, `pasajero3`, `ccosto1`, `ccosto2`, `ccosto3`, `valor`, `indiv1`, `indiv2`, `indiv3`, `peaje`, `regreso`, `espera`, `czona`, `recorrido`, `total`, `obs`, `comprobante`, `exportado` FROM `viajes` WHERE `exportado`=False"<br>
Else<br>
AccessDataSource1.SelectCommand = "SELECT `revisado`, `aprobado`, `Id`, `fecha`, `hora`, `empresa`, `tipo`, `legajo`, `desde`, `hasta`, `pasajero1`, `pasajero2`, `pasajero3`, `ccosto1`, `ccosto2`, `ccosto3`, `valor`, `indiv1`, `indiv2`, `indiv3`, `peaje`, `regreso`, `espera`, `czona`, `recorrido`, `total`, `obs`, `comprobante`, `exportado` FROM `viajes` WHERE `exportado`=False AND `legajo`=" & DropDownList1.SelectedValue<br>
End If<br>
ElseIf RadioButtonList1.SelectedValue = "Empresas" Then<br>
DropDownList1.Visible = False<br>
DropDownList2.Visible = True<br>
Label1.Visible = True<br>
Label1.Text = "Seleccione una Empresa"<br>
If DropDownList2.SelectedValue = Nothing Then<br>
AccessDataSource1.SelectCommand = "SELECT `revisado`, `aprobado`, `Id`, `fecha`, `hora`, `empresa`, `tipo`, `legajo`, `desde`, `hasta`, `pasajero1`, `pasajero2`, `pasajero3`, `ccosto1`, `ccosto2`, `ccosto3`, `valor`, `indiv1`, `indiv2`, `indiv3`, `peaje`, `regreso`, `espera`, `czona`, `recorrido`, `total`, `obs`, `comprobante`, `exportado` FROM `viajes` WHERE `exportado`=False"<br>
Else<br>
AccessDataSource1.SelectCommand = "SELECT `revisado`, `aprobado`, `Id`, `fecha`, `hora`, `empresa`, `tipo`, `legajo`, `desde`, `hasta`, `pasajero1`, `pasajero2`, `pasajero3`, `ccosto1`, `ccosto2`, `ccosto3`, `valor`, `indiv1`, `indiv2`, `indiv3`, `peaje`, `regreso`, `espera`, `czona`, `recorrido`, `total`, `obs`, `comprobante`, `exportado` FROM `viajes` WHERE `exportado`=False AND `empresa`=" & DropDownList2.SelectedValue<br>
End If<br>
End If<br>
'AccessDataSource1.UpdateCommand = "UPDATE `viajes` SET `revisado` = ?, `aprobado` = ?,`fecha` = ?, `hora` = ?, `empresa` = ?, `tipo` = ?, `legajo` = ?, `desde` = ?, `hasta` = ?, `pasajero1` = ?, `pasajero2` = ?, `pasajero3` = ?, `ccosto1` = ?, `ccosto2` = ?, `ccosto3` = ?, `valor` = ?, `indiv1` = ?, `indiv2` = ?, `indiv3` = ?, `peaje` = ?, `regreso` = ?, `espera` = ?, `czona` = ?,`recorrido` = ?,`total` = ?, `obs` = ?, `comprobante` = ?, `exportado` = ? WHERE `Id` = ?"<br>
GridView1.DataBind()<br>
End Sub
Related
I'm trying to create a registration form with python tkinter sqlite3, but I have a problem, when I do the update of just one record, all the names are updated (not just the one that was selected), and I have also this issue when I try do add new data: c.execute("INSERT INTO SCHOOL VALUES (:ID, :NAME, :BIRTH, :DOCS, :FATHER, :MOTHER, :CLASS)", sqlite3.IntegrityError: UNIQUE constraint failed: SCHOOL.CLASS, and I cant add more than 2 records.
I would like some help to solve this problem, this is the code:
from tkinter import *
from tkinter import ttk
import _sqlite3
root = Tk()
root.title('trying again')
root.geometry("1000x500")
data = [["1", "BOB", "27/10/2020", "234512", "JOHN", "DOE", "6º"],
]
# conectar a database
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS SCHOOL (
ID text,
NAME txt,
BIRTH txt,
DOCS txt,
FATHER txt,
MOTHER txt,
CLASS txt
oid PRIMARY KEY)
""")
# aDD RECORD TO TABLE
for record in data:
c.execute("INSERT OR IGNORE INTO SCHOOL VALUES (:ID, :NAME, :BIRTH, :DOCS, :FATHER, :MOTHER, :CLASS)",
{
'ID': str(record[0]),
'NAME': str(record[1]),
'BIRTH': str(record[2]),
'DOCS': str(record[3]),
'FATHER': str(record[4]),
'MOTHER': str(record[5]),
'CLASS': str(record[6])
}
)
conn.commit()
conn.close()
def query_database():
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("SELECT oid, * FROM SCHOOL")
records = c.fetchall()
global count
count = 0
for record in records:
if count % 2 == 0:
my_tree.insert(parent='', index='end', iid=count, text='',
values=(
record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[0]),
tags=('evenrow',))
else:
my_tree.insert(parent='', index='end', iid=count, text='',
values=(
record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[0]),
tags=('oddrow',))
count += 1
print(records)
conn.commit()
conn.close()
style = ttk.Style()
style.theme_use('default')
style.configure("Treeview",
background="#D3D3D3",
foreground="black",
rowheigth=25,
filedbackground="#D3D3D3")
style.map('Treeview',
background=[('selected', "#347083")])
tree_frame = Frame(root)
tree_frame.pack(pady=10)
tree_scroll = Scrollbar(tree_frame)
tree_scroll.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll)
my_tree.pack()
tree_scroll.config(command=my_tree.yview)
my_tree['columns'] = ("ID", "NAME", "BIRTH", "DOCS", "FATHER", "MOTHER", "CLASS", "OID")
my_tree.column("#0", width=0, stretch=NO)
my_tree.column("ID", anchor=W, width=140)
my_tree.column("NAME", anchor=W, width=140)
my_tree.column("BIRTH", anchor=CENTER, width=100)
my_tree.column("DOCS", anchor=W, width=140)
my_tree.column("FATHER", anchor=W, width=140)
my_tree.column("MOTHER", anchor=W, width=140)
my_tree.column("CLASS", anchor=W, width=140)
my_tree.column("OID", anchor=W, width=50)
my_tree.heading("#0", text="", anchor=W)
my_tree.heading("ID", text="ID", anchor=W)
my_tree.heading("NAME", text="NAME", anchor=W)
my_tree.heading("BIRTH", text="BIRTH", anchor=CENTER)
my_tree.heading("DOCS", text="DOCS", anchor=W)
my_tree.heading("FATHER", text="FATHER", anchor=W)
my_tree.heading("MOTHER", text="MOTHER", anchor=W)
my_tree.heading("CLASS", text="CLASS", anchor=W)
my_tree.heading("OID", text="OID", anchor=W)
my_tree.tag_configure('oddrow', background="white")
my_tree.tag_configure('evenrow', background="lightblue")
data_frame = LabelFrame(root, text="INFORMATION")
data_frame.pack(fill="x", expand="yes", pady=20)
fn_ID = Label(data_frame, text="ID")
fn_ID.grid(row=0, column=0, padx=10, pady=10)
fn_ID = Entry(data_frame)
fn_ID.grid(row=0, column=1, padx=10, pady=10)
fn_NAME = Label(data_frame, text="NAME")
fn_NAME.grid(row=0, column=2, padx=10, pady=10)
fn_NAME = Entry(data_frame)
fn_NAME.grid(row=0, column=3, padx=10, pady=10)
fn_BIRTH = Label(data_frame, text="DOCS")
fn_BIRTH.grid(row=0, column=4, padx=10, pady=10)
fn_BIRTH = Entry(data_frame)
fn_BIRTH.grid(row=0, column=5, padx=10, pady=10)
fn_DOCS = Label(data_frame, text="FATHER")
fn_DOCS.grid(row=1, column=0, padx=10, pady=10)
fn_DOCS = Entry(data_frame)
fn_DOCS.grid(row=1, column=1, padx=10, pady=10)
fn_FATHER = Label(data_frame, text="MOTHER")
fn_FATHER.grid(row=1, column=2, padx=10, pady=10)
fn_FATHER = Entry(data_frame)
fn_FATHER.grid(row=1, column=3, padx=10, pady=10)
fn_MOTHER = Label(data_frame, text="CLASS")
fn_MOTHER.grid(row=1, column=4, padx=10, pady=10)
fn_MOTHER = Entry(data_frame)
fn_MOTHER.grid(row=1, column=5, padx=10, pady=10)
fn_OID = Label(data_frame, text="OID")
fn_OID.grid(row=0, column=6, padx=10, pady=10)
fn_OID = Entry(data_frame)
fn_OID.grid(row=0, column=7, padx=10, pady=10)
fn_CLASS = Label(data_frame, text="BIRTH")
fn_CLASS.grid(row=1, column=6, padx=10, pady=10)
fn_CLASS = Entry(data_frame)
fn_CLASS.grid(row=1, column=7, padx=10, pady=10)
# add records:
def add_records():
my_tree.insert(parent='', index='end', text='',
values=(
fn_ID.get(), fn_NAME.get(), fn_CLASS.get(), fn_BIRTH.get(), fn_DOCS.get(),
fn_FATHER.get(),
fn_MOTHER.get(), fn_OID.get()), )
# update records:
def update_records():
select = my_tree.focus()
my_tree.item(select, text="", values=(
fn_ID.get(), fn_NAME.get(), fn_CLASS.get(), fn_BIRTH.get(), fn_DOCS.get(), fn_FATHER.get(),
fn_MOTHER.get(),
), )
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("""UPDATE OR IGNORE SCHOOL SET
ID=:ID,
NAME=:NAME,
BIRTH=:BIRTH,
DOCS=:DOCS,
MOTHER=:MOTHER,
CLASS=:CLASS
WHERE oid=oid""",
{
'ID': fn_ID.get(),
'NAME': fn_NAME.get(),
'BIRTH': fn_BIRTH.get(),
'DOCS': fn_DOCS.get(),
'FATHER': fn_FATHER.get(),
'MOTHER': fn_MOTHER.get(),
'CLASS': fn_CLASS.get(),
}
)
conn.commit()
conn.close()
# MOVE UP
def up():
rows = my_tree.selection()
for row in rows:
my_tree.move(row, my_tree.parent(row), my_tree.index(row) - 1)
# MOVE DOWN
def down():
rows = my_tree.selection()
for row in reversed(rows):
my_tree.move(row, my_tree.parent(row), my_tree.index(row) + 1)
# DELETE RECORDS SPECIFIC
def remove_one():
x = my_tree.selection()
for record in x:
my_tree.delete(record)
def remove_all():
for record in my_tree.children():
my_tree.delete(record)
# delete all
def clear_record():
fn_ID.delete(0, END)
fn_NAME.delete(0, END)
fn_CLASS.delete(0, END)
fn_BIRTH.delete(0, END)
fn_DOCS.delete(0, END)
fn_FATHER.delete(0, END)
fn_MOTHER.delete(0, END)
fn_CLASS.delete(0, END)
# SELECT RECORD
def select_record(e):
fn_ID.delete(0, END)
fn_NAME.delete(0, END)
fn_CLASS.delete(0, END)
fn_BIRTH.delete(0, END)
fn_DOCS.delete(0, END)
fn_FATHER.delete(0, END)
fn_MOTHER.delete(0, END)
fn_CLASS.delete(0, END)
fn_OID.delete(0, END)
selected = my_tree.focus()
values = my_tree.item(selected, 'values')
# insert values
fn_ID.insert(0, values[0])
fn_NAME.insert(0, values[1])
fn_CLASS.insert(0, values[2])
fn_BIRTH.insert(0, values[3])
fn_DOCS.insert(0, values[4])
fn_FATHER.insert(0, values[5])
fn_MOTHER.insert(0, values[6])
fn_OID.insert(0, values[7])
# add butons:
button_frame = LabelFrame(root, text="COMANDOS")
button_frame.pack(fill="x", expand="yes", padx=20)
update_button = Button(button_frame, text="changing data", command=update_records)
update_button.grid(row=0, column=0, padx=10, pady=10)
add_button = Button(button_frame, text="add data", command=add_records)
add_button.grid(row=0, column=1, padx=10, pady=10)
remove_button = Button(button_frame, text="remove data", command=remove_one)
remove_button.grid(row=0, column=2, padx=10, pady=10)
select_button = Button(button_frame, text="clear data", command=clear_record)
select_button.grid(row=0, column=3, padx=10, pady=10)
move_button = Button(button_frame, text="move row down", command=down)
move_button.grid(row=0, column=4, padx=10, pady=10)
move_button = Button(button_frame, text="move row up", command=up)
move_button.grid(row=0, column=5, padx=10, pady=10)
# delete_button = Button(button_frame, text="remover tudo",command=remove_all)
# delete_button.grid(row=0, column=7, padx=10, pady=10)
my_tree.bind("<ButtonRelease-1>", select_record)
query_database()
root.mainloop()
so I've been developing an asp.net web site and it has cascading dropdown. I didn't use ajax extender for cascading dropdown. here is the html mark up of my project
SPOILER, it has lot and lot of checkboxes, that's why i really need to have a workaround for checkboxes or postbacks..
<form id="form1" runat="server">
<div class = "header" runat = "server">
<div class = "osv"></div>
</div>
<div class = "center">
<div class = "box">
<table id = "spot">
<tr>
<td><asp:Label ID="LBLPlatform" runat="server" Text="Platform :"></asp:Label></td>
<td><asp:DropDownList ID="DDLPlatform" runat="server" CssClass = "ddl" AutoPostBack="True" >
<asp:ListItem Text="Platform" Value="Platform" ></asp:ListItem>
<asp:ListItem Text="First Person" Value="F1"></asp:ListItem>
<asp:ListItem Text="3rd Person" Value="F3"></asp:ListItem>
<asp:ListItem Text="Role Playing" Value="RP"></asp:ListItem>
<asp:ListItem Text="Multiplayer" Value="MP"></asp:ListItem>
<asp:ListItem Text="Single Player" Value="SP"></asp:ListItem>
</asp:DropDownList>
</td>
<td><asp:Label ID="LBLDate" runat="server" Text="Date :"></asp:Label></td>
<td><asp:TextBox ID="DDLDate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="LBLAgency" runat="server" Text="Agency :"></asp:Label></td>
<td><asp:DropDownList ID="DDLAgency" runat="server" AutoPostBack="true" CssClass = "ddl" >
<asp:ListItem Text="Agency"></asp:ListItem>
</asp:DropDownList></td>
<td><asp:Label ID="LBLReference" runat="server" Text="Reference :"></asp:Label></td>
<td><asp:TextBox ID = "TXTReference" runat = "server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="LBLAdvertiser" runat="server" Text="Advertiser :"></asp:Label></td>
<td><asp:DropDownList ID="DDLAdvert" runat="server" AutoPostBack="true" CssClass = "ddl" >
<asp:ListItem Text="Advertiser" ></asp:ListItem>
</asp:DropDownList></td>
<td><asp:Label ID = "LBLProgram" runat = "server" Text = "Program"></asp:Label></td>
<td><asp:DropDownList ID = "DDLProg" runat = "server" CssClass = "ddl"></asp:DropDownList></td>
</tr>
<tr>
<td><asp:Label ID = "LBLProduct" runat = "server" Text = "Product :"></asp:Label></td>
<td><asp:DropDownList ID="DDLProd" runat="server" AutoPostBack="true" CssClass = "ddl" >
<asp:ListItem Text="Product"></asp:ListItem>
</asp:DropDownList></td>
<td><asp:Label ID = "LBLTeldate" runat = "server" Text = "Telecast Date :"></asp:Label></td>
<td><asp:TextBox ID="datepicker" runat="server" onclick="return datepicker_onclick()" AutoPostBack="true" ></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="LBLVerleng" runat="server" Text="Version/Length :"></asp:Label></td>
<td><asp:DropDownList ID="DDLVer" runat="server" CssClass = "ddl" EnableViewState="true" AppendDataBoundItems="True"> </asp:DropDownList>
</td>
<td><asp:Label ID="LBLAe" runat="server" Text="Account Executive :"></asp:Label></td>
<td><asp:TextBox ID="TXTAe" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="LBLCost" runat="server" Text="Cost :"></asp:Label></td>
<td><asp:TextBox ID="TXTCost" runat="server"></asp:TextBox></td>
</tr>
</table>
this is my code behind where it loads the cascading ddls
Protected Sub dbchose() Handles DDLPlatform.SelectedIndexChanged
If IsPostBack Then
Select Case DDLPlatform.SelectedValue
Case "Platform"
DDLAgency.DataSource = New List(Of String)
DDLAgency.DataBind()
DDLAgency.Items.Add("Agency")
DDLAdvert.DataSource = New List(Of String)
DDLAdvert.DataBind()
DDLAdvert.Items.Add("Advertiser")
DDLProd.DataSource = New List(Of String)
DDLProd.DataBind()
DDLProd.Items.Add("Product")
DDLVer.DataSource = New List(Of String)
DDLVer.DataBind()
DDLVer.Items.Add("Version - Length")
DDLProg.DataSource = New List(Of String)
DDLProg.DataBind()
DDLProg.Items.Add("Program")
Case "F1"
Session("platform") = "F1"
Dim conn As New SqlConnection(Session("cs").ToString)
Dim que As String = "Select ag_agencde, ag_agennme from agency where ag_stat= 'A' order by ag_agennme asc"
Dim cmd As New SqlCommand(que, conn)
conn.Open() 'loading of agency per platform
DDLAgency.DataSource = cmd.ExecuteReader
DDLAgency.DataTextField = "ag_agennme"
DDLAgency.DataValueField = "ag_agencde"
DDLAgency.DataBind()
conn.Close()
'-- Loading List of Program per Platform - BMS
Dim que2 As String = "select pg_prgcode, pg_prgname from program where pg_status='A' order by pg_prgname ASC"
Dim cmd2 As New SqlCommand(que2, conn)
conn.Open()
DDLProg.DataSource = cmd2.ExecuteReader
DDLProg.DataTextField = "pg_prgname"
DDLProg.DataValueField = "pg_prgcode"
DDLProg.DataBind()
conn.Close()
'--
Case "F3"
Session("platform") = "F3"
Dim conn As New SqlConnection(Session("cs").ToString)
Dim que As String = "Select ag_agencde, ag_agennme from agency where ag_stat='A' order by ag_agennme asc"
Dim cmd As New SqlCommand(que, conn)
conn.Open() 'loading of agency per platform
DDLAgency.DataSource = cmd.ExecuteReader
DDLAgency.DataTextField = "ag_agennme"
DDLAgency.DataValueField = "ag_agencde"
DDLAgency.DataBind()
conn.Close()
'--loading of F3 programs
Dim que2 As String = "select pg_prgcode, pg_prgname from program where pg_status = 'A' order by pg_prgname ASC "
Dim cmd2 As New SqlCommand(que2, conn)
conn.Open()
DDLProg.DataSource = cmd2.ExecuteReader
DDLProg.DataTextField = "pg_prgname"
DDLProg.DataValueField = "pg_prgcode"
DDLProg.DataBind()
'--
Case "RP"
Session("platform") = "RP"
Dim conn As New SqlConnection(Session("cs").ToString)
Dim que As String = "Select ag_agencde, ag_agennme from agency where ag_stat='A' order by ag_agennme asc"
Dim cmd As New SqlCommand(que, conn)
conn.Open()
'--
DDLAgency.DataSource = cmd.ExecuteReader
DDLAgency.DataTextField = "ag_agennme"
DDLAgency.DataValueField = "ag_agencde"
DDLAgency.DataBind()
conn.Close()
'--loading of program per plaform - News TV
Dim que2 As String = "select pg_prgcode, pg_prgname from program where pg_status='A' order by pg_prgname ASC"
Dim cmd2 As New SqlCommand(que2, conn)
conn.Open()
DDLProg.DataSource = cmd2.ExecuteReader
DDLProg.DataTextField = "pg_prgname"
DDLProg.DataValueField = "pg_prgcode"
DDLProg.DataBind()
conn.Close()
'--
Case "MP"
Session("platform") = "Radio"
Dim conn As New SqlConnection(Session("cs").ToString)
Dim que As String = "Select ag_agencde, ag_agennme from agency where ag_stat='A' order by ag_agennme asc"
Dim cmd As New SqlCommand(que, conn)
conn.Open()
'--
DDLAgency.DataSource = cmd.ExecuteReader
DDLAgency.DataTextField = "ag_agennme"
DDLAgency.DataValueField = "ag_agencde"
DDLAgency.DataBind()
conn.Close()
'--loading of program for radio
Dim que2 As String = "select pg_prgcode, pg_prgname from program where pg_stat='A' order by pg_prgname ASC"
Dim cmd2 As New SqlCommand(que2, conn)
conn.Open()
DDLProg.DataSource = cmd2.ExecuteReader
DDLProg.DataTextField = "pg_prgname"
DDLProg.DataValueField = "pg_prgcode"
DDLProg.DataBind()
conn.Close()
'--
Case "SP"
Session("platform") = "SP"
Dim conn As New SqlConnection(Session("cs").ToString)
Dim que As String = "Select ag_agencde, ag_agennme from agency where ag_stat='A' order by ag_agennme asc"
Dim cmd As New SqlCommand(que, conn)
conn.Open()
'--
DDLAgency.DataSource = cmd.ExecuteReader
DDLAgency.DataTextField = "ag_agennme"
DDLAgency.DataValueField = "ag_agencde"
DDLAgency.DataBind()
conn.Close()
'--loading of programs Pinoy TV
Dim que1 As String = "select pg_prgcode, pg_prgname from program where pg_status='A' order by pg_prgname ASC"
Dim cm2 As New SqlCommand(que1, conn)
conn.Open()
DDLProg.DataSource = cm2.ExecuteReader
DDLProg.DataTextField = "pg_prgname"
DDLProg.DataValueField = "pg_prgcode"
DDLProg.DataBind()
End Select
End If
End Sub
Protected Sub agen_choose() Handles DDLAgency.SelectedIndexChanged
If IsPostBack = True Then
Select Case Session("platform").ToString
Case "F1"
Dim que As String = "select ad_advcde, ad_advnme from advertiser where ad_stat='A' order by ad_advnme ASC"
Dim cmd2 As New SqlCommand(que, conn)
conn.Open()
DDLAdvert.DataSource = cmd2.ExecuteReader
DDLAdvert.DataTextField = "ad_advnme"
DDLAdvert.DataValueField = "ad_advcde"
DDLAdvert.DataBind()
conn.Close()
'--
''--
Case "F3"
Dim cs As String = "server=SQLREP;database=F3;uid=sa;password=sa;"
conn.ConnectionString = cs
Dim que As String = "select ad_advcde, ad_advnme from advertiser where ad_stat='A' order by ad_advnme ASC"
Dim cmd2 As New SqlCommand(que, conn)
conn.Open()
DDLAdvert.DataSource = cmd2.ExecuteReader
DDLAdvert.DataTextField = "ad_advnme"
DDLAdvert.DataValueField = "ad_advcde"
DDLAdvert.DataBind()
conn.Close()
'--
Case "RP"
Dim que As String = "select ad_advcde, ad_advnme from RPSA.advertiser where ad_stat='A' order by ad_advnme ASC"
Dim cmd2 As New SqlCommand(que, conn)
conn.Open()
DDLAdvert.DataSource = cmd2.ExecuteReader
DDLAdvert.DataTextField = "ad_advnme"
DDLAdvert.DataValueField = "ad_advcde"
DDLAdvert.DataBind()
conn.Close()
'--
Case "Radio"
Dim que As String = "select ad_advcde, ad_advnme from advertiser where ad_stat='A' order by ad_advnme ASC"
Dim cmd2 As New SqlCommand(que, conn)
conn.Open()
DDLAdvert.DataSource = cmd2.ExecuteReader
DDLAdvert.DataTextField = "ad_advnme"
DDLAdvert.DataValueField = "ad_advcde"
DDLAdvert.DataBind()
conn.Close()
Case "SP"
Dim que As String = "select ad_advcde, ad_advnme from SPSA.advertiser where ad_stat='A' order by ad_advnme ASC"
Dim cmd2 As New SqlCommand(que, conn)
conn.Open()
DDLAdvert.DataSource = cmd2.ExecuteReader
DDLAdvert.DataTextField = "ad_advnme"
DDLAdvert.DataValueField = "ad_advcde"
DDLAdvert.DataBind()
conn.Close()
End Select
End If
End Sub
Protected Sub adver_choose() Handles DDLAdvert.SelectedIndexChanged
Dim conn As New SqlConnection(Session("cs").ToString)
If IsPostBack = True Then
Select Case Session("platform").ToString
Case "F1"
Dim que3 As String = "select p_pcode, p_pname from product where p_stat = 'A' and p_advcde = " & DDLAdvert.SelectedValue & " order by p_pname asc"
Dim cmd3 As New SqlCommand(que3, conn)
conn.Open()
DDLProd.DataSource = cmd3.ExecuteReader
DDLProd.DataTextField = "p_pname"
DDLProd.DataValueField = "p_pcode"
DDLProd.DataBind()
conn.Close()
'--
DDLProd.Items.Add("Product")
'--
Case "F3"
Dim que3 As String = "select p_pcode, p_pname from product where p_stat='A' and p_advcde = " & DDLAdvert.SelectedValue & " order by p_pname asc"
Dim cmd3 As New SqlCommand(que3, conn)
conn.Open()
DDLProd.DataSource = cmd3.ExecuteReader
DDLProd.DataTextField = "p_pname"
DDLProd.DataValueField = "p_pcode"
DDLProd.DataBind()
conn.Close()
'--
DDLProd.Items.Add("Product")
'--
Case "RP"
Dim que3 As String = "select p_pcode, p_pname from RPSA.product where p_stat='A' and p_advcde = " & DDLAdvert.SelectedValue & " order by p_pname asc"
Dim cmd3 As New SqlCommand(que3, conn)
conn.Open()
DDLProd.DataSource = cmd3.ExecuteReader
DDLProd.DataTextField = "p_pname"
DDLProd.DataValueField = "p_pcode"
DDLProd.DataBind()
conn.Close()
'--
DDLProd.Items.Add("Product")
'--
'--
Case "Radio"
Dim que3 As String = "select p_pcode, p_pname from product where p_stat='A' and p_advcde = " & DDLAdvert.SelectedValue & " order by p_pname asc"
Dim cmd3 As New SqlCommand(que3, conn)
conn.Open()
DDLProd.DataSource = cmd3.ExecuteReader
DDLProd.DataTextField = "p_pname"
DDLProd.DataValueField = "p_pcode"
DDLProd.DataBind()
conn.Close()
'--
DDLProd.Items.Add("Product")
'--
'--
Case "SP"
Dim que3 As String = "select p_pcode, p_pname from SPSA.product where p_stat='A' and p_advcde = " & DDLAdvert.SelectedValue & " order by p_pname asc"
Dim cmd3 As New SqlCommand(que3, conn)
conn.Open()
DDLProd.DataSource = cmd3.ExecuteReader
DDLProd.DataTextField = "p_pname"
DDLProd.DataValueField = "p_pcode"
DDLProd.DataBind()
conn.Close()
'--
DDLProd.Items.Add("Product")
'--
End Select
End If
End Sub
Protected Sub get_prod_ver() Handles DDLProd.SelectedIndexChanged
Dim conn As New SqlConnection(Session("cs").ToString)
If Not IsPostBack = True Then
Select Case Session("platform").ToString
Case "F1"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
DDLVer.Items.Add("Version")
'--
Case "F3"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
DDLVer.Items.Add("Version")
'--
Case "RP"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from RPSA.version where v_vpcode = (select p_pcode from RPSA.product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
Case "Radio"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
Case "SP"
Dim que11 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from SPSA.version where v_vpcode = (select p_pcode from RPSA.product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd41 As New SqlCommand(que11, conn)
conn.Open()
DDLVer.DataSource = cmd41.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
End Select
Else
Select Session("platform").ToString
Case "F1"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.ClearSelection()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
DDLVer.Items.Add("Version")
'--
Case "F3"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.ClearSelection()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
DDLVer.Items.Add("Version")
'--
Case "RP"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from RPSA.version where v_vpcode = (select p_pcode from RPSA.product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.ClearSelection()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
Case "Radio"
Dim que1 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from version where v_vpcode = (select p_pcode from product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd4 As New SqlCommand(que1, conn)
conn.Open()
DDLVer.ClearSelection()
DDLVer.DataSource = cmd4.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
Case "SP"
Dim que11 As String = "select v_version +' Lenght:' + convert(varchar(10), v_spotlen) as 'Version And Lenght', v_vpcode from SPSA.version where v_vpcode = (select p_pcode from RPSA.product where p_pcode='" & DDLProd.SelectedValue & "')"
Dim cmd41 As New SqlCommand(que11, conn)
conn.Open()
DDLVer.ClearSelection()
DDLVer.DataSource = cmd41.ExecuteReader
DDLVer.DataTextField = "Version And Lenght"
DDLVer.DataValueField = "v_vpcode"
DDLVer.DataBind()
conn.Close()
'--
DDLVer.Items.Add("Version")
End Select
End If
End Sub
my problem is the DDLVer is resetting its index on EVERY POSTBACKS!
if tried putting if not ispostback before the functionality nothing happens but when i ran it in debug mode, vb skips it and proceeds to end if.
second, i tried putting different conditions such as if ispostback = true, if ispostback, if not ispostback =true, but no luck..
i have been developing asp.net pages for the last 2 months and this problem with ddlver is eating 1 week on my plotted schedule..
please if there are any workaround for this let me know.
i am tired looking and reading same articles over and over again..
*bows
here is my page load event
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.MaintainScrollPositionOnPostBack = True
DDLVer.AppendDataBoundItems = True
If Not IsPostBack Then
Call sess_load()
Txtto.Enabled = False
Txtbg.Enabled = False
Txtencoded.Enabled = False
DDLDate.Text = Date.Today.Date
Txtfreq.Enabled = False
Txtdate.Enabled = False
Txtto1.Enabled = False
TextBox4.Enabled = False
Txtencoded.Enabled = False
End If
as you can see, im not binding any ddl on page_load event
well, what is weird with this. the ddl has the same index value so on postbacks, they will revert to the very first item. so make sure that when you load items in ddls check the ID that you will put and make sure they are unique
I´m doing a website in VB.NET that allows users to create and view profiles. For the first two users, the profile shows perfectly, but for any user with an ID number equal or higher than three it doesn't work. What could be the reason for that and how can I fix it?
This is the code that loads the profile in a webform:
Public Sub cargarPerfil(cnn As SqlConnection, cmd As SqlCommand)
Dim perfil, nombre, nick, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String
Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, credito As String
Dim da As New SqlDataAdapter
Dim dt As DataTable
perfil = "SELECT USUARIONOMBREREAL, USUARIONICK, PAISNOMBRE AS PAIS, CIUDADNOMBRE AS CIUDAD, USUARIOCODIGO, USUARIOTELEFONO, USUARIONACIMIENTO, " & _
"TIPONOMBRE AS TIPO1, NIVELNOMBRE AS NIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIOFOTO, USUARIOCREDITO, " & _
"RANGONOMBRE AS RANGO, TITULONOMBRE AS TITULO1 FROM USUARIO " & _
"INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID " & _
"INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID " & _
"INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID " & _
"INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID " & _
"INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID " & _
"INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
nombre = dt.Rows.Item(0).Item("USUARIONOMBREREAL")
nick = dt.Rows.Item(0).Item("USUARIONICK")
pais = dt.Rows.Item(0).Item("PAIS")
ciudad = dt.Rows.Item(0).Item("CIUDAD")
codigo = dt.Rows.Item(0).Item("USUARIOCODIGO")
telefono = dt.Rows.Item(0).Item("USUARIOTELEFONO")
nacimiento = dt.Rows.Item(0).Item("USUARIONACIMIENTO")
tipo1 = dt.Rows.Item(0).Item("TIPO1")
nivel = dt.Rows.Item(0).Item("NIVEL")
social = dt.Rows.Item(0).Item("USUARIOSOCIAL")
artistico = dt.Rows.Item(0).Item("USUARIOARTISTICO")
comercial = dt.Rows.Item(0).Item("USUARIOCOMERCIAL")
rango = dt.Rows.Item(0).Item("RANGO")
titulo1 = dt.Rows.Item(0).Item("TITULO1")
foto = "~/0/" + nombre + ".jpg"
credito = dt.Rows.Item(0).Item("USUARIOCREDITO")
dt = Nothing
perfil = "SELECT TIPONOMBRE AS TIPO2, TITULONOMBRE AS TITULO2 FROM USUARIO " & _
"INNER JOIN TIPO ON USUARIO.USUARIOTIPO2 = TIPO.TIPOID " & _
"INNER JOIN TITULO ON USUARIO.USUARIOTITULO2 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
tipo2 = dt.Rows.Item(0).Item("TIPO2")
titulo2 = dt.Rows.Item(0).Item("TITULO2")
dt = Nothing
perfil = "SELECT TITULONOMBRE AS TITULO3 FROM USUARIO INNER JOIN TITULO ON USUARIO.USUARIOTITULO3 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
titulo3 = dt.Rows.Item(0).Item("TITULO3")
dt = Nothing
lblNombre.Text = nombre
lblNick.Text = nick
lblPais.Text = pais
lblCiudad.Text = ciudad
lblCodigo.Text = codigo
lblTelefono.Text = telefono
lblNacimiento.Text = nacimiento
lblTipo1.Text = tipo1
lblTipo2.Text = tipo2
lblNivel.Text = nivel
lblSocial.Text = social
lblArtistico.Text = artistico
lblComercial.Text = comercial
lblRango.Text = rango
lblTitulo1.Text = titulo1
lblTitulo2.Text = titulo2
lblTitulo3.Text = titulo3
imgPerfil.ImageUrl = foto
lblCredito.Text = credito
End Sub
This is the code that creates profiles in a different webform:
Private Sub registro(cnn As SqlConnection, cmd As SqlCommand)
Dim nuevo, nombre, nick, pass, mail, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String
Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, contrato As String
Dim savePathF As String = "F:\ComparteME\ComparteME\0\"
Dim savePathC As String = "F:\ComparteME\ComparteME\Reconocimientos\"
Dim fileNameF As String = txtNombreReal.Text + ".jpg"
Dim fileNameC As String = "Reconocimiento - " + txtNombreReal.Text + ".jpg"
Dim pathToCheckF As String = savePathF + fileNameF
Dim pathToCheckC As String = savePathC + fileNameC
Dim tempfileNameF As String = ""
Dim tempfileNameC As String = ""
nuevo = ""
nombre = txtNombreReal.Text
nick = txtNick.Text
pass = txtPassword.Text
mail = txtMail.Text
pais = ddlPais.SelectedValue
ciudad = ddlCiudad.SelectedValue
codigo = txtCodigo.Text
telefono = txtTelefono.Text
nacimiento = txtNacimiento.Text
nivel = ddlNivel.SelectedValue
tipo1 = ddlTipo1.SelectedValue
tipo2 = ddlTipo2.SelectedValue
foto = ""
contrato = ""
social = 0
artistico = 0
comercial = 0
rango = 1
titulo1 = 0
titulo2 = 0
titulo3 = 0
If (uplFoto.HasFile) Then
If (System.IO.File.Exists(pathToCheckF)) Then
Dim counter As Integer = 0
While (System.IO.File.Exists(pathToCheckF))
tempfileNameF = counter.ToString() + fileNameF
pathToCheckF = savePathF + tempfileNameF
counter = counter + 1
End While
If counter > 0 Then
fileNameF = tempfileNameF
End If
End If
savePathF += fileNameF
uplFoto.SaveAs(savePathF)
foto = savePathF
End If
If (uplReconocimiento.HasFile) Then
If (System.IO.File.Exists(pathToCheckC)) Then
Dim counter As Integer = 0
While (System.IO.File.Exists(pathToCheckC))
tempfileNameC = counter.ToString() + fileNameC
pathToCheckC = savePathC + tempfileNameC
counter = counter + 1
End While
If counter > 0 Then
fileNameC = tempfileNameC
End If
End If
savePathC += fileNameC
uplReconocimiento.SaveAs(savePathC)
contrato = savePathC
End If
nuevo = "INSERT INTO USUARIO (USUARIOID, USUARIONOMBREREAL, USUARIONICK, USUARIOPASSWORD, USUARIOENCRIPTADO, USUARIOCORREO, USUARIOPAIS, USUARIOCIUDAD, USUARIOCODIGO, USUARIOTELEFONO, " & _
"USUARIONACIMIENTO, USUARIOTIPO1, USUARIOTIPO2, USUARIONIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIORANGO, USUARIOTITULO1, USUARIOTITULO2, " & _
"USUARIOTITULO3, USUARIOFOTO, USUARIOCONTRATO) " & _
"SELECT (ISNULL(MAX(USUARIOID), 0)+1), '" & nombre & "', '" & nick & "', '" & pass & "', PWDENCRYPT('" & pass & "'), '" & mail & "', " & pais & ", " & ciudad & ", " & codigo & ", " & _
"" & telefono & ", '" & nacimiento & "', " & tipo1 & ", " & tipo2 & ", " & nivel & ", " & social & ", " & artistico & ", " & comercial & ", " & rango & ", " & _
"" & titulo1 & ", " & titulo2 & ", " & titulo3 & ", '" & foto & "', '" & contrato & "' FROM USUARIO "
cnn.Open()
cmd.CommandText = nuevo
cmd.Connection = cnn
cmd.ExecuteNonQuery()
cnn.Close()
lblSuccess.Text = "¡Bienvenido a ComparteME! En un momento se comprobarán tus datos y tu cuenta será activada. Intenta iniciar sesión."
tblRegistro.Visible = False
tblSuccess.Visible = True
End Sub
Even when I do the query directly in SQLServer, it only loads the data when ID < 3, not any higher. SQL is like this:
SELECT
USUARIONOMBREREAL,
USUARIONICK,
PAISNOMBRE AS PAIS,
CIUDADNOMBRE AS CIUDAD,
USUARIOCODIGO,
USUARIOTELEFONO,
USUARIONACIMIENTO,
TIPONOMBRE AS TIPO1,
NIVELNOMBRE AS NIVEL,
USUARIOSOCIAL,
USUARIOARTISTICO,
USUARIOCOMERCIAL,
USUARIOFOTO,
USUARIOCREDITO,
RANGONOMBRE AS RANGO,
TITULONOMBRE AS TITULO1
FROM
USUARIO
INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID
INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID
INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID
INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID
INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID
INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID
WHERE
USUARIOID = '1' AND USUARIONICK = 'SpuntikPPV'
Since a lot of information is missing, I'm going to guess.
I think one of the tables you are joining to has just two records that join to your first two users. The other users do not have matching records in the other tables so they are omitted.
sqlqrystrng = "UPDATE temp_user_details set user_name = #username, user_email = #useremail, user_contact = #usercontact, user_address=#useraddress WHERE user_id = #userida"
sqlqrystrng2 = "UPDATE user_type set user_password = #userpassword where user_id = #useridb"
string_cnct = sqlqrystrng & sqlqrystrng2
conn.open
cmd = New SqlCommand(string_cnct, conn)
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#userida"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#useridb"
cmd.Parameters.Item("#userida").Value = struserid
cmd.Parameters.Item("#useridb").Value = struserid
sqlqrystrng = "UPDATE temp_user_details set user_name = #username, user_email =
useremail, user_contact = #usercontact, user_address=#useraddress WHERE user_id =
userida"
sqlqrystrng2 = " UPDATE user_type set user_password = #userpassword where user_id = #useridb"
string_cnct = sqlqrystrng & sqlqrystrng2
conn.open
cmd = New SqlCommand(string_cnct, conn)
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#userida"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#useridb"
cmd.Parameters.Item("#userida").Value = struserid
cmd.Parameters.Item("#useridb").Value = struserid
You need to add space before Update in second string
Updated Code
VB CODEBEHIND
Protected Sub cmdclick_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdclick.Click
Dim strConnString As String = WebConfigurationManager.ConnectionStrings("orca").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand("usp_validatecard", con)
cmd.CommandType = Data.CommandType.StoredProcedure
Dim GetTrack1 As String = ""
Dim GetTrack2 As String = ""
Dim SplitTrack As String = txtTrack.Text
If SplitTrack.Length.ToString = 19 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
GetTrack2 = Mid(SplitTrack, 10, 9)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 8 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 11 Then
GetTrack2 = Mid(SplitTrack, 2, 9)
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
Else
lblmessage.Text = "Could Not Find Any Tracks"
End If
MSSQL STORED PROCEDURE
ALTER Procedure [dbo].[usp_validatecard](
#memnum nvarchar(50) = '-',
#memname nvarchar(50) = '-',
#track1 nvarchar(50) = '-',
#track2 nvarchar(50) = '-',
#msgtrack1 nvarchar(50) = 'Track 1 is Blank',
#msgtrack2 nvarchar(50) = 'Track 2 is Blank',
#message nvarchar(100)= '-')
As
--select #cardid = '%128255? ;282556587?'
--select #track1 = '128255'
--select #track2 = '282556587'
-- track1 good, track2 good
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2))
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
if exists(select * from dbo.clubmembers where membershipid = #memnum and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Card is GOOD'
else
select #msgtrack1 = 'Track 1 is GOOD but In-active', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Check Member Status in Membership'
end
-- track1 good and track2 bad
Else
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2))
begin
select #memname = lastname, #memnum = FAMILYID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2)
if exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2) and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is GOOD but In-Active', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card and Check Member Status in Membership'
end
else
-- track1 bad, track2 good
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1)
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1 and STATUS = 'ACTIVE')
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Please re-encode card and Check member status in Membership'
end
select #memname, #memnum, #msgtrack1, #msgtrack2, #message
If you check if sp has two elements or not by doing
If sp.Length = 2 Then
...
End If
and inside the If block, you can do
Dim track1 as String = sp(0)
Dim track2 as String = sp(1)
C# is more to my liking but this is a rough cut of a method that will split your string, test for correct number of elements and then create database connection (assumed sql server but any ole db should work) and call your stored procedure.
Public Sub ProcessSwipe(ByVal value As String)
Dim splitValues() As String
Dim separator As Char = ";"
Dim connectionString As String = String.Empty
Dim storedProcName As String = String.Empty
' Edit these to sane values
connectionString = "Provider=SQLOLEDB;BData Source=localhost;Initial Catalog=msdb;Integrated Security=SSPI;"
storedProcName = "dbo.SaveSwipe"
If String.IsNullOrEmpty(value) Then
MsgBox("No value provided from swipe")
Return
End If
Try
splitValues = value.Split(separator)
If splitValues.Length <> 2 Then
MsgBox(String.Format("Splitting of swipe data did not result in 2 values. Swiped value is {0}", value))
Return
End If
' At this point, we should have an array with 2 elements in it
' Open a connection
Using connection As New OleDb.OleDbConnection(connectionString)
connection.Open()
Using Command As New OleDb.OleDbCommand
Command.CommandText = storedProcName
Command.CommandType = CommandType.StoredProcedure
Command.Connection = connection
' Assumes your proc takes 2 parameters, named swipe1 and swipe2
' Update to sane values
Command.Parameters.AddWithValue("#swipe1", splitValues(0))
Command.Parameters.AddWithValue("#swipe2", splitValues(1))
' Make the actual call to your stored procedure
Command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(String.Format("Attempt to split {0} failed. {1}", value, ex))
End Try
End Sub
Sub Main()
Dim shorty As String
Dim works As String
Dim longun As String
Dim nuthin As String
shorty = "%128565?"
works = "%128565?;229584115?"
longun = "%128565?;229584115?%128565?;229584115?"
nuthin = Nothing
ProcessSwipe(shorty)
ProcessSwipe(works)
ProcessSwipe(longun)
ProcessSwipe(nuthin)
End Sub