how to update database colum with checkbox in gridview vb.net - asp.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

Related

How to delete a row in gridview that was added dynamically using asp.net and vb.net

I have a gridview. the rows are added dynamically
Protected Sub btnAddCustomer_Click(sender As Object, e As EventArgs) Handles btnAddCustomer.Click
Dim dtSource As New DataTable
dtSource = CType(ViewState("dtSource"), DataTable)
Dim dr As DataRow = dtSource.NewRow()
dr("Id") = DropDownList3.SelectedIndex
dr("Name") = DropDownList3.SelectedItem
dtSource.Rows.Add(dr)
ViewState("dtSource") = dtSource
GridView1.DataSource = dtSource
GridView1.DataBind()
GridView1.HeaderRow.Cells(1).Text = "ID"
GridView1.HeaderRow.Cells(2).Text = "NAME"
End Sub
Each row has a delete image button, and when it is clicked it fires the Code:
Protected Sub GridVeiw1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If ViewState("dtSource") IsNot Nothing Then
Dim dtSource As New DataTable
Dim drCurrentRow As DataRow = Nothing
Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
dtSource = DirectCast(ViewState("dtSource"), DataTable)
If dtSource.Rows.Count > 0 Then
dtSource.Rows.RemoveAt(rowIndex)
drCurrentRow = dtSource.NewRow()
dtSource.AcceptChanges()
ViewState("dtSource") = dtSource
GridView1.DataSource = dtSource
GridView1.DataBind()
End If
End If
End Sub
The delete procedure is not working!!!
Any suggessions Please?
I read the question regarding How to delete a row in GV, but it is not helping because am not deleting from GV but from DataTable that contains the data for the GV

Unable to show the saved data in gridview

I have a dropdown in gridview, which gets data through web method,but after saving data, i am unable to show saved data in gridview.
Here is the code behind for gridview bind through web method:
Private Sub BindData()
Dim objTable As New DataTable("ProjectInfoClass")
objTable = objWebService.BindProjectInfo
projectInfoList.Clear()
For Each dr As DataRow In objTable.Rows
projectInfoList.Add(New ProjectInfoClass With {.ProjectNumber = dr("ProjectNumber").ToString(), .ProjectId = dr("ProjectId").ToString(), .ProjectName = dr("ProjectName").ToString(), .ProjectModifiedDate = dr("ProjectModifiedDate").ToString(), .RecordUpdatedDate = dr("RecordUpdatedDate").ToString(), .ProjectLocation = dr("ProjectLocation").ToString(), .LocationServerName = dr("LocationServerName").ToString(), .ProjectModifiedBy = dr("ProjectModifiedBy").ToString(), .DBServer = dr("DBServer").ToString(), .DBName = dr("DBName").ToString(), .Flag = Nothing})
Next
GridView1.DataSource = objTable
GridView1.DataBind()
End Sub
Save method
For Each objectList In projectInfoList
If objectList.Dirty = True And objectList.Flag = Nothing Then
objWebService.UpdateProjectInfo(objectList)
Label1.Text = "Record updated successfully"
ElseIf objectList.Flag = "I" And objectList.Dirty = True Then
objWebService.InsertProjectInfo(objectList)
Label1.Text = "Record inserted successfully"
End If
Next
BindData()
btnEdit.Enabled = True
btnSave.Enabled = False
btnAddNewRow.Enabled = False
End Sub
Here is the code behind to bind dropdown which calls the web method:
Public Sub BindDataDropDown()
For Each grdRow As GridViewRow In GridView1.
Dim dropDown As DropDownList = DirectCast(GridView1.Rows(grdRow.RowIndex).Cells(7).FindControl("ddlProjectModifiedBy"), DropDownList)
dropDown.DataSource = objWebService.BindDropDown()
dropDown.DataValueField = "EmpId"
dropDown.DataTextField = "EmpName"
dropDown.DataBind()
Next
End Sub
rowdatabound
Protected Sub ddlProjectModifiedBy_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
BindDataDropDown()
End Sub
indexchange
Protected Sub ddlProjectModifiedBy_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gv As DropDownList = TryCast(sender, DropDownList)
Dim row As GridViewRow = gv.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectInfoList.Item(rowindex).ProjectModifiedBy = gv.SelectedItem.ToString()
projectInfoList.Item(rowindex).Dirty = True
End Sub
What should i write in the rowbound event of grid to hold selected data of dropdown in gridview?
Call the drop down binding method BindDataDropDown() after you have successfully saved the changes to the database.

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

What's wrong with this ASP.NET code.... ? (Datagrid + Imagebutton)

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Hold" Then
Dim gvRow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim index As Integer = gvRow.RowIndex
Dim myRow As GridViewRow = GridView1.Rows(index)
'Find the checkbox
Dim lab5 As Label = DirectCast(myRow.FindControl("Label5"), Label)
Dim label2 As Label = DirectCast(myRow.FindControl("Label2"), Label)
Dim label4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
Dim label22 As Label = DirectCast(myRow.FindControl("Label22"), Label)
Me.Response.Redirect("Select_seats.aspx?s_no=" & label22.Text.ToString & "&" & "journey=" & Label6.Text & "&" & "seater=" & label4.Text & "&" & "sleeper=" & label2.Text & "&" & "service=" & lab5.Text.ToString)
End If
End Sub
this code giving error :
in this line
im gvRow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
error :
Unable to cast object of type 'ASP.vendors_select_service_aspx' to type 'System.Web.UI.WebControls.GridViewRow'.
Why do you iterate all rows in Grid? Therefore you are redirecting on the first row and not on the row that causes the "Hold-Command". The NamingContainer of any control in the GridViewRow is the GridViewRow itself and this is what FindControl needs to get the reference to your labels.
If e.CommandName = "Hold" Then
Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, Control).NamingContainer, GridViewRow)
Dim lab5 As Label = DirectCast(row.FindControl("Label5"), Label)
Dim label2 As Label = DirectCast(row.FindControl("Label2"), Label)
Dim label4 As Label = DirectCast(row.FindControl("Label4"), Label)
Dim label6 As Label = DirectCast(row.FindControl("label6"), Label)
Dim label22 As Label = DirectCast(row.FindControl("Label22"), Label)
Me.Response.Redirect("Select_seats.aspx?s_no=" & label22.Text.ToString & "&" & "journey=" & label6.Text & "&" & "seater=" & label4.Text & "&" & "sleeper=" & label2.Text & "&" & "service=" & lab5.Text.ToString)
End If
The answer of theChrisKent is the right direction, assuming you're using TemplateField you can get the index with such code:
Dim gvRow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim index As Integer = gvRow.RowIndex
If still no luck do as you were already told and post your .aspx code so we can help instead of groping in the dark.
Switch your code to this:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Hold" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim myRow As GridViewRow = GridView1.Rows(index)
'Find the checkbox
Dim lab5 As Label = DirectCast(myRow.FindControl("Label5"), Label)
Dim label2 As Label = DirectCast(myRow.FindControl("Label2"), Label)
Dim label4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
Dim label22 As Label = DirectCast(myRow.FindControl("Label22"), Label)
Me.Response.Redirect("Select_seats.aspx?s_no=" & label22.Text.ToString & "&" & "journey=" & Label6.Text & "&" & "seater=" & label4.Text & "&" & "sleeper=" & label2.Text & "&" & "service=" & lab5.Text.ToString)
End If
End Sub
Also add this (be sure to switch the holdButton retrieval code to match the control type and index you are using)
Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowCreated
' The GridViewCommandEventArgs class does not contain a
' property that indicates which row's command button was
' clicked. To identify which row's button was clicked, use
' the button's CommandArgument property by setting it to the
' row's index.
If e.Row.RowType = DataControlRowType.DataRow Then
' Retrieve the LinkButton control from the first column.
Dim holdButton As LinkButton = CType(e.Row.Cells(0).Controls(0), LinkButton)
' Set the LinkButton's CommandArgument property with the
' row's index.
holdButton.CommandArgument = e.Row.RowIndex.ToString()
End If
End Sub
This code taken from an example here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=VS.80).aspx

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