Want DropDownlist value to get stored by ID - asp.net

I am working on asp.net using VB and SQL database
I have two tables mst_Emp & mst_dept
mst_dept got following columns (dpt_ID(PK),dpt_name,dpt_descrip)
mst_Emp got following columns (Emp_ID,Emp_FirstName,Emp_LastName,Emp_Address,Emp_ContactNo,Dept_ID(Foreign key),Marital_Status,Gender)
Now I have a Employee Detail Form in that I have Department Name label(DataBind from mst_Dept) and I have DropDownList for that to select. If some choose value from DropDownList I want it to get stored by Dept_ID in database. How can I do that ?

Try binding your Department Dropdownlist like
Using sqlconn As New SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)
If sqlconn.State = ConnectionState.Closed Then
sqlconn.Open()
End If
Dim ds As New DataSet()
Dim qry As String = "Select dpt_ID,dpt_name from mst_Dept"
Using cmd As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd)
sda.Fill(ds)
D_ddlDepartment.DataSource = ds
D_ddlDepartment.DataValueField = "dpt_ID"
D_ddlDepartment.DataTextField = "dpt_name"
D_ddlDepartment.DataBind()
D_ddlDepartment.Items.Insert(0, "-- Select Department --")
If sqlconn.State = ConnectionState.Open Then
sqlconn.Close()
End If
End Using
End Using
and you can access the Dept_id like
Dim Deptid As Integer = Convert.ToInt32(D_ddlDepartment.SelectedValue)

FINALLY GOT IT THANKS :-)
Dim ds As New DataSet
Dim cmd1 As SqlCommand = New SqlCommand()
Dim sqlconn As SqlConnection = New SqlConnection()
sqlconn.ConnectionString = "Data Source=PRGM\SQLEXPRESS;Initial Catalog=HRMS;Integrated Security=True"
sqlconn.Open()
cmd1 = New SqlCommand("select Dpt_ID,Dpt_Name from mst_Dept", sqlconn)
'Dim qry As String = "select Dpt_ID,Dpt_Name from mst_Dept"
'cmd1 As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd1)
sda.Fill(ds)
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataValueField = ds.Tables(0).Columns("Dpt_ID").ColumnName
DropDownList1.DataTextField = ds.Tables(0).Columns("Dpt_Name").ColumnName
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, "-- Select Department --")
sqlconn.Close()
End If

Related

Data table + session = Shopping cart

GM everybody
i'm finding some issues in the implementation of my shopping cart
The query works but it doesn't store information in session.
Will i fix the query or the problem is the session ?
Here the code :
Dim constr As String = ConfigurationManager.ConnectionStrings("!aCommerce-ConnectionString!").ConnectionString
' Query SQL
Using cmd As New SqlCommand("SELECT Id,NomeProdotto, PrezzoProdotto, Quantità FROM aProdotti WHERE ID='" + Request.QueryString("ID").ToString + "' OR ID='" + Request.QueryString("ID").ToString + "'")
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
Session("dt") = dt
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
change you code to below
Dim constr As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection()
con.ConnectionString = constr
con.Open()
' Query SQL
Using cmd As New SqlCommand("SELECT Id,PromoCode as NomeProdotto,PromoCodeMessage as PrezzoProdotto, PromoCodeLimit as Quantità FROM EventPromocodetbl WHERE ID=" & Request.QueryString("ID").ToString & "", con)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Dim SessionDt As New DataTable()
SessionDt = Session("dt")
If Not SessionDt Is Nothing Then
If (dt.Rows.Count > 0) Then
Dim dr As DataRow
dr = SessionDt.NewRow()
dr("Id") = dt.Rows(0)("Id").ToString()
dr("NomeProdotto") = dt.Rows(0)("NomeProdotto").ToString
dr("PrezzoProdotto") = dt.Rows(0)("PrezzoProdotto").ToString
dr("Quantità") = dt.Rows(0)("Quantità").ToString
SessionDt.Rows.Add(dr)
End If
Session("dt") = SessionDt
GridView1.DataSource = SessionDt
GridView1.DataBind()
Else
Session("dt") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Using
End Using
Problem is you are assigning blank DatatTable to session and then you are filling that DataTable using DataAdapter fill method that is issue.

What's wrong with my Count Query asp.net

Public state_name as String
state_name = Textbox1.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=" & state_name
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using
The code shows an error
Invalid column name 'California'.
But California is already present in my State table, I want to count all the cities comes under state_name= california which I have entered in my State table.
I want the output as
California (3)
You want to use Parameterized Query to avoid SQL Injection.
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=#State_Name"
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#State_Name", state_name)
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using
Because you didn't surround your variable with quotes. "state_name = '" + state_name + "'"
But, you should use a parameter instead.

Trouble getting date value

I am modifying a webpage. Webpage is using visual basic and my database is a SQL database.
The webpage gives me the total Sick, Comp, and Vacation time off. Right now, I get the logon name of whoever's logged onto the computer, and I look up the EmployeeID in a tblEmployees so I can search tblTimeAvailable by the EmployeeID, and then add up the different times.
I want to also get the StartDate from tblEmployees so I can also search by anniversary date (after I calculate it from the Start Date). I'm getting an error "Value of type 'Integer' cannot be converted to 'Date' on the rvsd=command2.ExecuteNonQuery line. Here's my code:
Dim rve As Object
Dim rvsd As Date
Dim dt As Date = Today
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim sqlstdt As String = "SELECT StartDate FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
Dim command2 As New SqlCommand(sqlstdt, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
command2.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
rve = command.ExecuteScalar
rvsd = command2.ExecuteNonQuery
End Using
Dim theDateThisYear As Date
theDateThisYear = DateSerial(Year(Now), Month(rvsd), Day(rvsd))
If theDateThisYear < Now() Then
theDateThisYear = DateAdd("yyyy", 1, theDateThisYear)
End If
Dim NextAnniversary As Date = theDateThisYear
MsgBox(NextAnniversary)
'Get Sick Time - DOES NOT INCLUDE CHECKING TO MAKE SURE LESS THAN ANNIV DATE YET
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #emp"
Dim command As New SqlCommand(sqls1, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#emp", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
rvsa = command.ExecuteScalar
End Using
Thanks in advance for any help you can give me!
Assuming that the column [StartDate] in the database has a type of DateTime then all you need to do is
rvsd = CDate(command2.ExecuteScalar)
Although you could have retrieved both values with one query:
SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
and so
Dim rve As String
Dim rvsd As Date
Dim connStr As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Dim sql = "SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(Sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
rve = rdr.GetString(0)
rvsd = rdr.GetDateTime(1)
End If
End Using
End Using

GridViewUpdateEventArgs not working with update to sql table

I'm not getting my GridViewUpdateEventArgs to work for some reason.
I'm trying to update my gridview(table in sql) but it´s not working.
And i don´t know how to write the the Where clause in the sql to match.
Public Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim SelectRow As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim RowID As HiddenField = Gridview1.FindControl("ID")
Dim Report As String = SelectRow.Cells(1).Text
Dim BusinessArea As String = SelectRow.Cells(2).Text
Dim Salesdepartment As String = SelectRow.Cells(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim SqlCommand As New SqlCommand("UPDATE TEST SET Report = ('" & Report & "'), [Business Area] = ('" & BusinessArea & "'), Salesdepartment = ('" & Salesdepartment & "') WHERE ID = #RowID ", SqlConnection)
Dim SqlDataAdapter As New SqlDataAdapter(SqlCommand)
Dim dataSet As New DataSet()
SqlDataAdapter.Fill(dataSet)
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
The "ID" column is my PK in the table and is in a (ItemTemplate) (Hidden)
In this Way SqlDataAdapter can't update database record, see here how to update record using SqlDataAdapter .
or you can try like this:
Dim row As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim hf As HiddenField = TryCast(row.FindControl("ID"), HiddenField)
Dim Report As [String] = row.Cell(1).Text
Dim BusinessArea As [String] = row.Cell(2).Text
Dim Salesdepartment As [String] = row.Cell(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim cmd As New SqlCommand("UPDATE TEST SET Report = #Report,[Business Area] =#BusinessArea, Salesdepartment=#Salesdepartment WHERE ID = #RowID ", SqlConnection)
cmd.Parameters.AddWithValue("#Report", Report)
cmd.Parameters.AddWithValue("#BusinessArea", BusinessArea)
cmd.Parameters.AddWithValue("#Salesdepartment", Salesdepartment)
cmd.Parameters.AddWithValue("#RowID", hf.Value)
cmd.ExecuteNonQuery()
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using

How can I use multiple Stored procedures on 1 Sub

I write a code to retrieve to show data from Stored Procedure with ASP.NET like this
Private Sub AutoNumberVerification()
Dim Conn As New SqlConnection(strConn.ToString)
Dim cmd As New SqlCommand()
Try
cmd.Connection = Conn
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
If (txtProducerID.Text.Trim.Length = 9) Then
cmd.CommandText = "spProductCount"
cmd.Parameters.AddWithValue("#ID", txtProducerID.Text)
End If
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Dim dr As SqlDataReader = cmd.ExecuteReader()
dt.Load(dr)
If (convertInteger(dt.Rows(0)("estbProducerID").ToString) > 0) Then
cmd.CommandText = "spProductCount"
rdoEstbProducerList.Items.FindByValue(convertInteger(dt.Rows(0)("estbProducerID"))).Selected = True
End If
cmd.CommandText = "spProductCount"
TextBox11.Text = dt.Rows(0)("ALL").ToString
TextBox4.Text = dt.Rows(0)("FOOD").ToString
TextBox5.Text = dt.Rows(0)("DRINKS").ToString
TextBox6.Text = dt.Rows(0)("TAILOR").ToString
TextBox7.Text = dt.Rows(0)("USABLE").ToString
TextBox8.Text = dt.Rows(0)("HERB").ToString
cmd.CommandText = "spProductproveCounts"
TextBox12.Text = dt.Rows(0)("REGISTERED").ToString
Catch ex As Exception
Response.Write("ERROR Load: " & ex.Message)
Finally
Conn.Close()
End Try
End Sub
but it show an error = "REGISTERED" is not belong to the table
how can I use two stored procedures?
Just setting the cmd.CommandText to a stored procedure name will not execute it. You still need to call ExecuteReader after each change to the CommandText

Resources