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.
Related
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
I have added Checkbox and Radio buttons as column values to the GridView in runtime.
Now, i am unable to fire Checkbox_CheckedChanged event upon Checkbox.checked
Any suggestions on how to call event ? Below is the Grid i implemented.
Below is the source code:
1) Grid Init
Dim COUNT As Integer = 0
For i As Integer = 0 To ListHeaderDataFieldArray.Count - 1
If ListHeaderDataFieldArray(i) = Me.CRMSignCond Then
Dim TemplateCol As New TemplateField
TemplateCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center
TemplateCol.ItemStyle.Width = New Unit(RowChildWidth)
TemplateCol.HeaderText = ListHeaderTextArray(i)
TemplateCol.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, ListHeaderDataFieldArray(i))
GridviewChild.Columns.Add(TemplateCol)
Else
If ListHeaderTextArray(i) = "Target Sign" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
ElseIf ListHeaderTextArray(i) = "Consolidate" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
ElseIf ListHeaderTextArray(i) = "Signing Group" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
Else
Dim colItem As BoundField = New BoundField
colItem.HeaderText = ListHeaderTextArray(i)
colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
End If
End If
2) Adding Controls to the GridView Columns in "RowDataBound" event.
Protected Sub GridviewChild_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridviewChild.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso Not String.IsNullOrEmpty(CRMSignCond) Then
Dim s As String = ""
Dim lbValue As Label = DirectCast(e.Row.Cells(5).FindControl("lbValue"), Label)
e.Row.Cells(5).Attributes.Add("onmousemove", "Show('" + lbValue.Text + "')")
e.Row.Cells(5).Attributes.Add("onmouseout", "this.style.backgroundColor=this.oldcolor;Hide();")
End If
Dim cbTargetSign As New CheckBox
Dim rbConsolidate As New RadioButton
Dim tbSignGrp As New TextBox
cbTargetSign.ID = "chkSelect"
cbTargetSign.AutoPostBack = True
rbConsolidate.ID = "rbConsolidate"
tbSignGrp.ID = "tbConsolidate"
tbSignGrp.Width = 25
If Not e.Row.RowIndex = -1 Then
e.Row.Cells(6).Controls.Add(cbTargetSign)
e.Row.Cells(4).Controls.Add(tbSignGrp)
For i As Integer = 0 To 1
rbConsolidate = New RadioButton()
If i = 0 Then
rbConsolidate.Text = "YES"
Else
rbConsolidate.Text = "NO"
End If
'ii.Location = New Point(20, tt)
'ii.Tag = fileArray(i)
'tt = tt + 20
rbConsolidate.GroupName = "Consolidate"
e.Row.Cells(7).Controls.Add(rbConsolidate)
Next
End If
End Sub
Regards,
VK
You are adding and binding events programmatically in code behind and adding them to the GridView. And since dynamic Controls need to be recreated on every time the page is loaded to function properly, you should make sure the RowDataBound event is triggered on every Page Load, and that includes a PostBack.
So I'm guessing you do this (like you would normally):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
GridView1.DataSource = mySource
GridView1.DataBind
End If
End Sub
Change it to
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
GridView1.DataSource = mySource
GridView1.DataBind
End Sub
I have a dropdown list which is inside a user control on my page.
When I select an item in a gridview it fills some data including this dropdown list selecting the correspondent value to the gridview row.
Then I can change the selection, but when i try to do that the Selected Index Changed event isn't firing. At least not at first. If i select again it fires.
I'm using asp.net with VB.
I have put AutoPostback = true, I've set the Handles in the codebehind method, I've set a default empty line and set it to default selection, but I can't get it to work.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Page.IsPostBack() Then
fillProd()
Dim cert As String = Session("var")
isFilled = Session("isFilled")
If Not IsNothing(cert) And Not isFilled Then
FillFields(cert)
End If
End If
End Sub
Private Sub fillProd()
dt = HttpContext.Current.Session("dt")
Dim row() As DataRow = dt.Select()
Dim dtProductos As New DataTable()
dtProductos.Columns.Add(New DataColumn("valorcombo", GetType(String)))
dtProductos.Columns.Add(New DataColumn("textocombo", GetType(String)))
Dim firstrow As DataRow = dtProductos.NewRow()
firstrow (0) = 0
firstrow (1) = ""
dtProductos.Rows.Add(firstrow)
For i As Integer = 0 To row.Length - 1
Dim fila As DataRow = dtProductos.NewRow()
fila(0) = row(i)("cod")
fila(1) = row(i)("text")
dtProductos.Rows.Add(fila)
Next
ddlproductos.DataSource = dtProductos
ddlproductos.DataTextField = "textocombo"
ddlproductos.DataValueField = "valorcombo"
ddlproductos.DataBind()
ddlproductos.SelectedIndex = 0
End Sub
Private Sub FillFields(cert As String)
Dim dtSubsData As DataTable = GetData(cert)
If Not IsNothing(dtSubsData) Then
Dim row As DataRow = dtSubsData.Rows(0)
ddlproductos.ClearSelection()
ddlproductos.SelectedValue = row("cod").ToString()
Session("isFilled") = True
isFilled = Session("isFilled")
End If
End Sub
Can anyone help?
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
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 :)