Add new data to textbox when selecting item from combobox - asp.net

How can I automatically input a number to a textbox after clicking a button upon selecting an item from a combobox. All I know to do is to get the data from the combobox to textbox. But what I would like to do is to add data to a textbox once the item is selected.
This is My Code:
Imports System.Data.OleDb
Imports System.Data
Public Class voting1
Dim con As New OleDbConnection
Dim Com As New OleDbCommand
Dim ComInsert As New OleDbCommand
Dim ComUpdate As New OleDbCommand
Dim ComDelete As New OleDbCommand
Dim aAdapter As New OleDbDataAdapter
Dim Dset As New DataSet
Private Sub voting1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ConProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
Try
Try
con.ConnectionString = ConProvider
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As Exception
MsgBox("No Connection Established")
End Try
Me.fill()
user.Visible = False
user.Text = Form1.usertxt.Text
Catch ex As Exception
End Try
End Sub
Private Sub fill()
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from candidate"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
While (dataRead.Read())
presbox.Items.Add(dataRead("President"))
vpbox.Items.Add(dataRead("VicePresident"))
secbox.Items.Add(dataRead("Secretary"))
treasbox.Items.Add(dataRead("Treasurer"))
End While
aAdapter.Dispose()
End Sub
Public Sub Initialize()
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As System.Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "ERROR CONNECTION")
End Try
End Sub
Private Sub bo()
Dim con1 As New OleDbConnection
Dim cmd As New OleDbCommand
con1.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
cmd.Connection = con1
con1.Open()
Dim num As Integer
cmd.CommandText = "SELECT pres1 FROM vote1"
If IsDBNull(cmd.ExecuteScalar) Then
num = 1
samp.Text = num
Else
num = 1
samp.Text = num
End If
cmd.Dispose()
con1.Close()
con1.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Call Initialize()
If presbox.Text = "" Or vpbox.Text = "" Or secbox.Text = "" Or treasbox.Text = "" Then
MsgBox("All Fields are required, Check the fields", MsgBoxStyle.Information, "Required Fiels")
Exit Sub
End If
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from [vote] where username = '" & user.Text & "'"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
If Not dataRead.HasRows Then
ComInsert.CommandText = "INSERT INTO vote([username],[president],[vicePresident],[secretary],[treasurer])" & _
"VALUES('" & user.Text & "','" & presbox.Text & "','" & vpbox.Text & "','" & secbox.Text & "','" & treasbox.Text & "')"
ComInsert.Connection = con
ComInsert.ExecuteNonQuery()
MsgBox("Voting Successful!", MsgBoxStyle.Information, "NEW RECORD")
Form1.Show()
Me.Close()
aAdapter.Dispose()
ComInsert.Dispose()
Else
MsgBox("WARNING: User Voted Already!!", MsgBoxStyle.Exclamation, "ERROR SAVING DATA")
Me.Close()
Form1.Show()
End If
Catch ex As Exception
End Try
End Sub
End Class

There are a couple of ways to do this if I am understanding what you are wanting.
1.) We can just check if there is anything in the combobox.text property.
If String.IsNullOrEmpty(cbobox.text) Then
Perform the logic of adding data to textbox here.
cbobox.text = null
End If
That is the most simple way, but you will have to set the combobox back to null after the data is added to make it work again.
2.) We can make use of the Combobox.SelectedIndexChanged method.
Here is the documentation website: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged.aspx
Here is an example:
private void ComboBox1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
perform logic here
}
Hope this helps.

Private Sub p1()
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Com = con.CreateCommand
Com.CommandText = "SELECT COUNT(vote.presnum) as countofpres FROM vote WHERE presnum ='1';"
Dim dt As OleDb.OleDbDataReader = Com.ExecuteReader
dt.Read()
Dim countpres As Integer = dt("countofpres")
Me.pres1.Text = countpres
dt.Close()
End Sub
here it is Jlott

Related

this code got error? why i cannot use this code do the register database

Imports System.Data.OleDb
Partial Class register
Inherits System.Web.UI.Page
Dim an As New OleDbConnection("provider=micromofy.jet.oledb.4.0;database=" & Server.MapPath("database/Database1.accdb"))
Protected Sub ImageButton1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click
Try
Dim cmd As New OleDbCommand("insert into reo{Name,Age,Contact,Gender,Address,Username,Password,Comfirm Password}values{a1,a2,a3,a4,a5,a6,a7,a8}", cn)
cmd.Parameters.AddWithValue("a1", TextBox1)
cmd.Parameters.AddWithValue("a2", TextBox2)
cmd.Parameters.AddWithValue("a3", TextBox3)
cmd.Parameters.AddWithValue("a4", TextBox4)
cmd.Parameters.AddWithValue("a5", TextBox5)
cmd.Parameters.AddWithValue("a6", TextBox6)
cmd.Parameters.AddWithValue("a7", TextBox7)
cmd.Parameters.AddWithValue("a8", TextBox8)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Label1.Text = "Data Saved"
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
Catch ex As Exception
cn.Close()
Label1.text = ex.Message
End Try
Server.Transfer("Login.aspx")
End Sub
End Class
If your connection string is sorted out...
Dim cmd As New OleDbCommand("insert into reo (Name,Age,Contact,Gender,Address,Username,Password,[Comfirm Password]) values (#a1,#a2,#a3,#a4,#a5,#a6,#a7,#a8)", cn)
cmd.Parameters.AddWithValue("#a1", TextBox1.Text)
etc.

SQL data not populating in asp webform

Currently can not get any SQL data to populate the web form. When I run the report in Visual Studio preview mode, the data populates, however when running through my web app it displays nothing.
Imports System.Data.SqlClient
Public Class topvendors
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
getEntity()
' startdate.Text = DateTime.Today.ToShortDateString
End If
End Sub
Protected Sub getEntity()
Dim strConnString As String = Session("strconnection") 'ConfigurationManager.ConnectionStrings("TrialConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "pGetProjectsByUser"
cmd.Parameters.Add("#employeeid", SqlDbType.Int).Value = Session("userid")
cmd.Parameters.Add("#reportid", SqlDbType.Int).Value = Request.QueryString("id")
cmd.Connection = con
Try
con.Open()
Dim dt As New DataTable()
Dim ds As New DataSet()
'Dim db As New SqlDataAdapter(cmd)
Dim da = New SqlDataAdapter(cmd)
da.Fill(ds)
'db.Fill(ds)
division.DataSource = ds.Tables(0)
division.DataTextField = "entityname"
division.DataValueField = "entitycode"
division.DataBind()
' If ds.Tables(0).Rows.Count > 1 Then
'divisions.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
' communities.DataValueField = "projID"
' communities.DataBind()
' Else
' divisions.Text = ds.Tables(0).Rows(0)("entityname").ToString
'division.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
'communities.DataValueField = "projID"
'communities.DataBind()
'End If
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
' Dim communities As String = Server.UrlEncode(Request.Form("communities"))
' Response.Write(communities)
' Dim removedays As Integer = Request.Form("removedays")
'getEntity()
' MsgBox(sort.SelectedValue)
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=Excel&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=PDF&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
End Class
Note: You are storing connection string in Session, it is not recommendable. You can do but it is better you should use web.config
file to store connection string.
You can be refer this: Avoid storing connection string in session for different sql schema
For Solution I recommended
You must check the session variable prior to getting the value for the connection string.
' Check if session is null
If Not (Session("strconnection ") Is Nothing) Then
{
//
}
When it is Null or Nothing or Empty, try to retrieve the connection string again.
You need to cast session variables into their correct types, before use like
Session("strconnection")
Replace it by
Session("strconnection").toString()
And
Cast Session("userid") and Request.QueryString("id") by the help of
Integer.Parse/ Integer.TryParse
you can read this for concept:
Return Value From Session

ASP.NET Session remains '0'

I have a masterpage that has this code in it:
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Session("userid") = Nothing Then
txtLoginUser.Visible = True
txtLoginPass.Visible = True
Else
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim useridComm As String = "SELECT name, surname FROM users WHERE user_id=#userid"
Dim sqlUserID As New SqlCommand
conn.Open()
Dim userid As String = Session("UserID")
sqlUserID = New SqlCommand(useridComm, conn)
sqlUserID.Parameters.AddWithValue("#userid", Convert.ToInt32(userid))
Dim datareader As SqlDataReader = sqlUserID.ExecuteReader()
datareader.Read()
If datareader.HasRows Then
userid = Session("UserID")
lblLoggedIn.Text = "[Welcome, " + datareader("name").ToString() & " " & datareader("surname").ToString() + " ]"
txtLoginUser.Visible = False
txtLoginPass.Visible = False
lblUsername.Visible = False
lblRegister.Visible = False
btnLogin.Visible = False
lblUsername0.Visible = False
End If
datareader.Close()
conn.Close()
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim loginSQL As New SqlCommand
Dim loginComm As String
Dim CommonFunctions As New CommonFunctions()
Dim dec_pass As String = CommonFunctions.EncryptPassword(txtLoginPass.Text.Trim)
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
loginComm = "SELECT user_id FROM users WHERE username=#username and password=#password"
conn.Open()
loginSQL = New SqlCommand(loginComm, conn)
loginSQL.Parameters.AddWithValue("#username", txtLoginUser.Text.ToString)
loginSQL.Parameters.AddWithValue("#password", dec_pass)
Dim dr As SqlDataReader = loginSQL.ExecuteReader()
dr.Read()
If dr.HasRows Then
Session("UserID") = dr("user_id")
ElseIf dr.HasRows = False Then
lblRegister.ForeColor = Drawing.Color.Red
lblRegister.Text = "Incorrect Username/Password."
End If
dr.Close()
conn.Close()
Response.Redirect("Default.aspx")
End Sub
</script>
On Button1 click the script should get the user_id by using the datareader and create a Session("UserID") and pass it to Default.aspx. Default.aspx then gets the Session("UserID") and searches for a user_id that has the same value and checks the roles using user_roles table, and if the role_id is 4 then tblAdmin is shown, otherwise, it isn't.
This is the code for Default.aspx:
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim UserID As Integer = Convert.ToInt32(Session("UserID"))
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim userTypeCommand As String = "SELECT role_id FROM users_role WHERE user_id=#UserID"
Dim userTypeSQL As New SqlCommand
conn.Open()
Try
userTypeSQL = New SqlCommand(userTypeCommand, conn)
userTypeSQL.Parameters.AddWithValue("#UserID", UserID)
Dim datareader As SqlDataReader = userTypeSQL.ExecuteReader
If datareader("role_id").ToString = "4" Then
tblAdmin.Enabled = True
tblAdmin.Visible = True
ElseIf datareader("role_id").ToString IsNot "4" Then
tblAdmin.Visible = False
End If
Catch ex As Exception
End Try
conn.Close()
End Sub
Protected Sub btnCreateArticle_Click(sender As Object, e As EventArgs) Handles btnCreateArticle.Click
Response.Redirect("addArticle.aspx")
End Sub
Protected Sub btnAdmin_Click(sender As Object, e As EventArgs) Handles btnAdmin.Click
Response.Redirect("Admin.aspx")
End Sub
End Class
When I debug, after I press the 'Login' button the user_id (Session('UserID') remains 0, when the user_id of the user I used to log with is '12' in the table.
What Am I doing wrong?
I am using ASP.NET/VB.NET and SQL Server 2012.
Fixed it. Had a missing datareader.Read().

How to pass only checked values form a list of check boxes in asp.net using vb

Im trying to pass only checked values to a database. But my problem is that even the unchecked values are being passed. My check boxes are created dynamically form a Dropdown box.
Creation of List box form a Drop Down Box
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim uname As String
Dim sqlConnection As New SqlConnection(connectionString)
sqlConnection.Open()
Dim exe1 As String = "select USERNAME from dummy_tbl_first AS L INNER JOIN Dummy_tbl_second AS A ON L.USER_ID= A.USER_ID INNER JOIN Dummy_tbl3 AS G ON G.GROUP_ID=A.GROUP_ID WHERE G.GROUP_NAME='" + DropDownList1.Text + "' ORDER BY USERNAME "
Dim thisCommand As New SqlCommand(exe1, sqlConnection)
thisCommand.ExecuteNonQuery()
Dim thisReader As SqlDataReader = thisCommand.ExecuteReader()
CheckBoxList1.Items.Clear()
While (thisReader.Read())
uname = thisReader.GetValue(0)
CheckBoxList1.Items.Add(uname)
End While
thisCommand.Dispose()
sqlConnection.Close()
Button1.Enabled = False
End Sub
And this is how i insert into database
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id As Integer = Request.QueryString("sr_id")
Dim first_name37 As String = CType(Session.Item("FIRST_NAME"), String)
Session("FIRST_NAME") = first_name37
Dim update_id As String = Request.QueryString("sr_id")
For Each list As ListItem In CheckBoxList1.Items
Response.Write(list.Selected)
Dim da As Date = Date.Now()
Dim sqlConnection As New SqlConnection(connectionString)
sqlConnection.Open()
Dim exe1 As String = "INSERT INTO TEST_TBL VALUES('" & id & " ','" + first_name37 + "','" + list.Value + "','" + da + "')"
Dim thisCommand As New SqlCommand(exe1, sqlConnection)
thisCommand.ExecuteNonQuery()
Dim exeupdate As String = "UPDATE TEST_TBL2 SET STATUS='ASSIGNED' WHERE CR_ID='" + update_id + "'"
Dim thisCommandUpdate As New SqlCommand(exeupdate, sqlConnection)
thisCommandUpdate.ExecuteNonQuery()
sqlConnection.Close()
Next
CheckBoxList1.Items.Clear()
Button1.Enabled = False
End Sub
Any help would be much appreciated. Thank you
You need to conditionalise your logic since now it's not discriminating at all. All of the items are in the CheckBoxList1.Items, not just the selected ones; so, check for selected items only...
If (list.Selected) Then
' proceed with this one
End If

How to check a check box automatically on vb.net asp.net?

i have to insert some data value and value like this picture on insert.aspx
And how i show like this to update the data update.aspx
So how to make check box on update.aspx check automatic like on insert.aspx
on Insert.aspx.vb
Protected Sub insertdata()
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_inserttrainer"
cmd.Parameters.AddWithValue("#id", txtKode.Text)
cmd.Parameters.AddWithValue("#nama", txtnama.Text)
cmd.Parameters.AddWithValue("#status", txtstatus.SelectedValue)
cmd.Parameters.AddWithValue("#alamat", txtalamat.Text)
cmd.Parameters.AddWithValue("#telp", txttel.Text)
cmd.Parameters.AddWithValue("#hp", txthp.Text)
cmd.Parameters.AddWithValue("#email", txtemail.Text)
cmd.ExecuteNonQuery()
cls.closeconnection()
End Sub
Protected Sub savedatamateri()
Dim cbterpilih As Boolean = False
Dim cb As CheckBox = Nothing
Dim n As Integer = 0
Do Until n = gridsecond.Rows.Count
cb = gridsecond.Rows.Item(n).FindControl("chkStatus")
If cb IsNot Nothing AndAlso cb.Checked Then
cbterpilih = True
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandText = "Insert Into m_trainer_detil (trainer_id, materi_id)"
cmd.CommandText &= "values(#triner, #materi)"
Dim com As HiddenField = CType(gridsecond.Rows(n).FindControl("HiddenField2"), HiddenField)
cmd.Parameters.AddWithValue("#triner", txtKode.Text)
cmd.Parameters.AddWithValue("#materi", com.Value)
cmd.ExecuteNonQuery()
cls.closeconnection()
End If
n += 1
Loop
End Sub
Protected Sub insert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles insert.Click
If txtalamat.Text = "" Then
labelran.Text = "Tolong isi Alamat"
ElseIf txtemail.Text = "" Then
labelran.Text = "Tolong isi Email"
ElseIf txtnama.Text = "" Then
labelran.Text = "Tolong isi Nama"
ElseIf txttel.Text = "" Then
labelran.Text = "Tolong isi Telepon"
ElseIf txthp.Text = "" Then
labelran.Text = "Tolong isi Handphone"
Else
insertdata()
savedatamateri()
listhendle()
End If
End Sub
and for update.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
listhendle()
listmateri()
End If
End Sub
Protected Sub listhendle()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_trainer] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
griddata.DataSource = ds
griddata.DataBind()
End Sub
Protected Sub listmateri()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_materi] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
gridsecond.DataSource = ds
gridsecond.DataBind()
End Sub
Protected Sub griddata_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles griddata.SelectedIndexChanging
Dim kode As HiddenField = CType(griddata.Rows(e.NewSelectedIndex).FindControl("HiddenField1"), HiddenField)
txtKode.Text = kode.Value
txtnama.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(1).Text, " ", "")
txtalamat.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(2).Text, " ", "")
txttel.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(3).Text, " ", "")
txthp.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(4).Text, " ", "")
txtstatus.SelectedValue = Replace(griddata.Rows(e.NewSelectedIndex).Cells(5).Text, " ", "")
txtemail.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(6).Text, " ", "")
End Sub
But i don't know how connect materi with database
Thank You
It looks like you are storing the materi_id in the table m_trainer. So it looks like you would need to set up an OnRowDataBound event on your "gridSecond" GridView. Within the OnRowDatabound event get a dataset for the selected trainer_id and if the materi_id exists within that dataset set its checked value as true.

Resources