Get the value of selected item in dropdownlist - asp.net

I added Item in dropdownlist and when I select the Item I added, it does not show up in Label1. Here is my code:
ASPX
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:DropDownList ID="drpOne" runat="server" AutoPostBack="true">
</asp:DropDownList>
VB
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
con.Open()
If Not IsPostBack Then
Dim Sql = "SELECT College FROM College"
cmdAdd = New SqlDataAdapter(Sql, con)
Dim ds As New DataSet()
cmdAdd.Fill(ds)
drpOne.DataSource = ds
drpOne.DataTextField = "College"
drpOne.DataValueField = "College"
drpOne.DataBind()
drpOne.Items.Insert(0, New ListItem("Please select College", ""))
drpOne.SelectedItem.Value = "Please select College"
drpOne.Items.Insert(0, New ListItem("All", ""))
end if
End Sub
Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
Label1.Text = drpOne.SelectedItem.Value
End Sub

i haven't checked the code, but try it this way
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
con.Open()
If Not IsPostBack Then
Dim Sql = "SELECT College FROM College"
cmdAdd = New SqlDataAdapter(Sql, con)
Dim ds As New DataSet()
cmdAdd.Fill(ds)
drpOne.AppendDataBoundItems = true
drpOne.Add(New ListItem("Please select College", ""))//You have passed "Please select College" as text and "" as value in ListItem
drpOne.Add(New ListItem("All", ""))
drpOne.DataSource = ds
drpOne.DataTextField = "College"
drpOne.DataValueField = "College"
drpOne.DataBind()
drpOne.Items.FindByText("Please select College").Selected = true
end if
End Sub
Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
Label1.Text = drpOne.SelectedItem.Value
End Sub

drpOne.SelectedItem.Text == "enter the value which you want to search"

DataValueField must set your primary key column Id , I think CollegeId is that .
drpOne.DataTextField = "College"
drpOne.DataValueField = "CollegeId"//Must set Integer value for dropdown item vale

Related

how to update database colum with checkbox in gridview vb.net

i have a checkbox in gridview rows...and have a database column name "Active" whose default value is "1"
i bind checkbox with database colum active...
when i click on checkbox by default its is checked because the default value of active in dbase column is 1 ..
I want when i uncheck checkbox the value updated on active column of selected row will be 0...and checkbox remains unchecked....
I have a code sippet but not working
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
For Each myRow As GridViewRow In GridView1.Rows
'Find the checkbox
Dim Chk1 As CheckBox = DirectCast(myRow.FindControl("CheckBox1"), CheckBox)
Dim id As HiddenField = DirectCast(myRow.FindControl("HiddenField1"), HiddenField)
Dim active As HiddenField = DirectCast(myRow.FindControl("HiddenField3"), HiddenField)
Dim SQLData As New MySql.Data.MySqlClient.MySqlConnection("server=localhost;User Id=root;Persist Security Info=True;database=clixngo")
Dim cmdSelect As New MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM my_state where id='" & id.Value & "'", SQLData)
SQLData.Open()
Dim dtrReader As MySql.Data.MySqlClient.MySqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
While dtrReader.Read()
Chk1.Checked = dtrReader("active")
End While
Else
End If
dtrReader.Close()
SQLData.Close()
Next
End Sub
Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
For Each myRow As GridViewRow In GridView1.Rows
Dim Chk1 As CheckBox = DirectCast(myRow.FindControl("CheckBox1"), CheckBox)
Dim id As HiddenField = DirectCast(myRow.FindControl("HiddenField1"), HiddenField)
Dim active As HiddenField = DirectCast(myRow.FindControl("HiddenField3"), HiddenField)
If Chk1.Checked = True Then
SqlDataSource1.UpdateParameters("id").DefaultValue = id.Value
SqlDataSource1.UpdateParameters("active").DefaultValue = "1"
SqlDataSource1.UpdateParameters("state").DefaultValue = "Andaman and Nicobar"
SqlDataSource1.Update()
ElseIf Chk1.Checked = False Then
SqlDataSource1.UpdateParameters("id").DefaultValue = id.Value
SqlDataSource1.UpdateParameters("active").DefaultValue = "0"
SqlDataSource1.UpdateParameters("state").DefaultValue = "Andaman and Nicobar"
SqlDataSource1.Update()
End If
Next
End Sub

GridView reloads all Record after Row Selection

At Page Load, I populate the GridView with records. Then I created a search functionality to search for records. The GridView is actually updating based on the search text. The problem is when I select a row, the GridView shows all the records and not the list based on search.
Here is the code:
Imports MySql.Data.MySqlClient
Public Class Main_Admin
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim myDataSet As DataSet
Dim strSQL As String
'Dim iRecordCount As Integer
myConnection = New MySqlConnection("server=localhost; user id=root; password=admin; database=db; pooling=false;")
strSQL = "SELECT emp_id AS 'Employee ID', emp_sname AS Surname, emp_fname AS 'First Name', emp_mname AS 'Middle Name', tbl_emp_cat.cat_name AS 'Category', nature AS 'Nature of Employment' FROM tbl_employee JOIN tbl_emp_cat ON tbl_employee.emp_cat = tbl_emp_cat.emp_cat;"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
myDataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "mytable")
GridView1.DataSource = myDataSet
GridView1.DataBind()
myConnection.Close()
End Sub
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
e.Row.Cells(0).Width = 100
e.Row.Cells(0).Attributes.CssStyle("text-align") = "center"
e.Row.Cells(1).Width = 100
e.Row.Cells(2).Width = 100
e.Row.Cells(3).Width = 100
e.Row.Cells(4).Width = 100
If (e.Row.RowType = DataControlRowType.DataRow) Then
'e.Row.Attributes("onmouseover") = "this.style.cursor='hand';"
e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"
e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" & Convert.ToString(e.Row.RowIndex))
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.textDecoration='underline';")
'e.Row.Attributes.Add("onmouseout", "this.style.textDecoration='none';")
'e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(Me.GridView1, Page.ClientScript.GetPostBackEventReference(GridView1, e.Row.RowIndex)))
' "Select$" + e.Row.RowIndex.ToString())
End If
End Sub
Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
GridView1.SelectedIndex = -1
End Sub
Private Sub search_Click(sender As Object, e As EventArgs) Handles search.Click
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim myDataSet As DataSet
Dim strSQL As String
'Dim iRecordCount As Integer
myConnection = New MySqlConnection("server=localhost; user id=root; password=admin; database=db; pooling=false;")
strSQL = "SELECT emp_id AS 'Employee ID', emp_sname AS Surname, emp_fname AS 'First Name', emp_mname AS 'Middle Name', tbl_emp_cat.cat_name AS 'Category', nature AS 'Nature of Employment' FROM tbl_employee JOIN tbl_emp_cat ON tbl_employee.emp_cat = tbl_emp_cat.emp_cat WHERE emp_sname LIKE '%" & search_text.Text + "%';"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
myDataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "mytable")
GridView1.DataSource = myDataSet
GridView1.DataBind()
myConnection.Close()
End Sub
End Class
A quick glance at your code shows that you are missing this line in you page load
If Not Page.IsPostBack Then
->put your code here
End if
Your grid view is being refreshed each time on page load wiping off your filtering functionality.Hope this helps.

Access Multiple Dynamic Dropdownlists selected Value - ASP.Net

I am adding multiple dynamic dropdownlists to my form.
I'm wanting to access the selected values of the dropdownlists on click of a button.
Private pnlDropDownList As Panel
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit
'Create a Dynamic Panel
pnlDropDownList = New Panel()
pnlDropDownList.ID = "pnlDropDownList"
pnlDropDownList.BorderWidth = 1
pnlDropDownList.Width = 300
Me.form1.Controls.Add(pnlDropDownList)
'Create a LinkDynamic Button to Add TextBoxes
Dim btnAddDdl As New Button
btnAddDdl.ID = "btnAddDdl"
btnAddDdl.Text = "Add DropDownList"
AddHandler btnAddDdl.Click, AddressOf btnAdd_Click
Me.form1.Controls.Add(btnAddDdl)
'Recreate Controls
RecreateControls("ddlDynamic", "DropDownList")
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim cnt As Integer = FindOccurence("ddlDynamic")
CreateDropDownList("ddlDynamic-" & Convert.ToString(cnt + 1))
End Sub
Private Function FindOccurence(ByVal substr As String) As Integer
Dim reqstr As String = Request.Form.ToString()
Return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length)
End Function
Private Sub RecreateControls(ByVal ctrlPrefix As String, ByVal ctrlType As String)
Dim ctrls As String() = Request.Form.ToString().Split("&"c)
Dim cnt As Integer = FindOccurence(ctrlPrefix)
If cnt > 0 Then
For k As Integer = 1 To cnt
For i As Integer = 0 To ctrls.Length - 1
If ctrls(i).Contains((ctrlPrefix & "-") + k.ToString()) AndAlso Not ctrls(i).Contains("EVENTTARGET") Then
Dim ctrlID As String = ctrls(i).Split("="c)(0)
If ctrlType = "DropDownList" Then
CreateDropDownList(ctrlID)
End If
Exit For
End If
Next
Next
End If
End Sub
Private Sub CreateDropDownList(ByVal ID As String)
Dim ddl As New DropDownList()
ddl.ID = ID
ddl.DataSource = Me.odsNames
ddl.DataTextField = "Name"
ddl.DataValueField = "ID"
ddl.DataBind()
ddl.Items.Insert(0, New ListItem("All", -1))
ddl.SelectedIndex = 0
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf OnSelectedIndexChanged
pnlDropDownList.Controls.Add(ddl)
Dim lt As New Literal()
lt.Text = "<br />"
pnlDropDownList.Controls.Add(lt)
End Sub
Protected Sub OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
'Not used, want to get Values from button click
End Sub
Protected Sub cmdAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdAdd.Click
Dim cnt As Integer = FindOccurence("ddlDynamic")
pnlDropDownList.Controls.Remove(pnlDropDownList.FindControl("ddlDynamic-" & Convert.ToString(cnt)))
End Sub
This is where I would like to check all dynamic dropdownlists and extract their selected values
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'' Check All dynamic Dropdownlists and retrieve selected values
End Sub
End Class
Any assistance would be much appreciated. thanks
You could use Linq to get the references of your dynamic DropDowns in the panel:
Dim allDdls = pnlDropDownList.Controls.OfType(Of DropDownList)()
For Each ddl In allDdls
Dim selectedValue = ddl.SelectedValue
Next

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.

Dynamic gridview columns event problem

i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row.
I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because:
_OnDataBound is not called on every postback (same for _OnRowDataBound)
_OnInit is not possible because the 'Inner table' for the Gridview is added after Init
_OnLoad is not possible because the 'selected' row is not selected yet.
I can add the columns to the dynamic GridView based on my ITemplate class.
But now the button events won't fire.... Any suggestions?
The dynamic adding of the gridview:
Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
Dim g As GridView = sender
g.DataBind()
If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count > 0 Then
Dim t As Table = g.Controls(0)
Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim c As New TableCell
Dim visibleColumnCount As Integer = 0
For Each d As DataControlField In g.Columns
If d.Visible Then
visibleColumnCount += 1
End If
Next
c.ColumnSpan = visibleColumnCount
Dim ph As New PlaceHolder
ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value))
c.Controls.Add(ph)
r.Cells.Add(c)
t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r)
End If
End Sub
Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView
Dim col As Interfaces.esColumnMetadata
Dim coll As New BLL.ViewStmCollection
Dim entity As New BLL.ViewStm
Dim query As BLL.ViewStmQuery = coll.Query
Me._gridStock.AutoGenerateColumns = False
Dim buttonf As New TemplateField()
buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button")
buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button")
buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button")
Me._gridStock.Columns.Add(buttonf)
For Each col In coll.es.Meta.Columns
Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name)
Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name)
Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name)
Dim f As New TemplateField()
f.HeaderTemplate = headerf
f.ItemTemplate = itemf
f.EditItemTemplate = editf
Me._gridStock.Columns.Add(f)
Next
query.Where(query.PnmAutoKey.Equal(PnmAutoKey))
coll.LoadAll()
Me._gridStock.ID = "gvChild"
Me._gridStock.DataSource = coll
AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand
Me._gridStock.DataBind()
Return Me._gridStock
End Function
The ITemplate class:
Public Class QuantityTemplateField : Implements ITemplate
Private _itemType As ListItemType
Private _fieldName As String
Private _infoType As String
Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String)
Me._itemType = ItemType
Me._fieldName = FieldName
Me._infoType = InfoType
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case Me._itemType
Case ListItemType.Header
Dim l As New Literal
l.Text = "<b>" & Me._fieldName & "</b>"
container.Controls.Add(l)
Case ListItemType.Item
Select Case Me._infoType
Case "Button"
Dim ib As New Button()
Dim eb As New Button()
ib.ID = "InsertButton"
eb.ID = "EditButton"
ib.Text = "Insert"
eb.Text = "Edit"
ib.CommandName = "Edit"
eb.CommandName = "Edit"
AddHandler ib.Click, AddressOf Me.InsertButton_OnClick
AddHandler eb.Click, AddressOf Me.EditButton_OnClick
container.Controls.Add(ib)
container.Controls.Add(eb)
Case Else
Dim l As New Label
l.ID = Me._fieldName
l.Text = ""
AddHandler l.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(l)
End Select
Case ListItemType.EditItem
Select Case Me._infoType
Case "Button"
Dim b As New Button
b.ID = "UpdateButton"
b.Text = "Update"
b.CommandName = "Update"
b.OnClientClick = "return confirm('Sure?')"
container.Controls.Add(b)
Case Else
Dim t As New TextBox
t.ID = Me._fieldName
AddHandler t.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(t)
End Select
End Select
End Sub
Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("insert click")
End Sub
Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("edit click")
End Sub
Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim boundValue As Object = Nothing
Dim ctrl As Control = sender
Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer
boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName)
Select Case Me._itemType
Case ListItemType.Item
Dim fieldLiteral As Label = sender
fieldLiteral.Text = boundValue.ToString()
Case ListItemType.EditItem
Dim fieldTextbox As TextBox = sender
fieldTextbox.Text = boundValue.ToString()
End Select
End Sub
End Class
Oh my oh my, I went to MVC, anybody reading this question should do the same :)

Resources