Dropdown not firing event on usercontrol - asp.net

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?

Related

Move grid rows up or down on button click

I have a grid that I am trying to move the grid rows either up or down based on button click. Here is what I have so far.
Protected Sub imgBtnMoveUp_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim imgBtn As ImageButton
Dim FirstRow As GridViewRow = gvQuoteSo.Rows(0)
Dim btnUp As Button = DirectCast(FirstRow.FindControl("MoveUp"), Button)
Dim gvrow As GridViewRow
Dim previousRow As GridViewRow
Dim index As Integer = 0
imgBtn = CType(sender, ImageButton)
If imgBtn.CommandName = "MoveUp" Then
index = Convert.ToInt32(imgBtn.CommandArgument)
gvrow = gvQuoteSo.Rows(index)
previousRow = gvQuoteSo.Rows(index - 1)
UpdatePanelGrid.Update()
End If
End Sub
When I click the button for up nothing hapens. I know this is just the move up function but if I can get help with that then the move down will answer itself. Thanks so much!
Explanations are given in comments.
Private Sub btnUp_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count ' will count the number of rows
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index ' row index of the selected cell
If idx = 0 Then ' for no rows selected
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index ' columns corresponding to the selected row
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row) ' Remove the corrent row
rows.Insert(idx - 1, row)' Re-insert the row
grid.ClearSelection()
grid.Rows(idx - 1).Cells(col).Selected = True
Catch
End Try
End Sub
Private Sub btnDown_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index
If idx = totalRows - 2 Then
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row)
rows.Insert(idx + 1, row)
grid.ClearSelection()
grid.Rows(idx + 1).Cells(col).Selected = True
Catch
End Try
End Sub

Persisting datatables in viewstate and databinding

I am passing in a start date, an end date, a SQL stored procedure, and a identifying area code into a shared function to populate five declared datatables.
Public Shared Function getNBOCAPData(ByVal startDate As DateTime, ByVal endDate As DateTime, ByVal sp As String, ByVal orgCode As String) As DataTable
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("CancerRegisterConnectionString").ConnectionString.ToString)
Dim sqlCmd As New SqlCommand
getNBOCAPData = New DataTable
Try
SqlConn.Open()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = SqlConn
sqlCmd.CommandTimeout = 300
sqlCmd.CommandText = sp
sqlCmd.Parameters.AddWithValue("#StartDate", startDate)
sqlCmd.Parameters.AddWithValue("#EndDate", endDate)
sqlCmd.Parameters.AddWithValue("#UserOrgCode", orgCode)
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
getNBOCAPData.Load(reader)
Catch ex As Exception
Common.LogError(ex, True)
Finally
SqlConn.Close()
SqlConn.Dispose()
End Try
End Function
The results of this function are then passed into the datatables like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim patiDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATI", Request.QueryString("orgCode"))
Dim tumDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_TUM", Request.QueryString("orgCode"))
Dim surDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_SUR", Request.QueryString("orgCode"))
Dim cheDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_CHE", Request.QueryString("orgCode"))
Dim patDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATH", Request.QueryString("orgCode"))
Dim hidCount As Integer = 0
If patiDataTable.Rows.Count = 0 Then
divPati.Visible = False
hidCount += 1
End If
If tumDataTable.Rows.Count = 0 Then
divTum.Visible = False
hidCount += 1
End If
If surDataTable.Rows.Count = 0 Then
divSur.Visible = False
hidCount += 1
End If
If cheDataTable.Rows.Count = 0 Then
divChe.Visible = False
hidCount += 1
End If
If pathDataTable.Rows.Count = 0 Then
divPath.Visible = False
hidCount += 1
End If
If hidCount = 5 Then
divNoResults.Visible = True
divInstructions.Visible = False
Else
ViewState("patiDataTable") = patiDataTable
ViewState("tumDataTable") = tumDataTable
ViewState("surDataTable") = surDataTable
ViewState("cheDataTable") = cheDataTable
ViewState("pathDataTable") = pathDataTable
End If
End Sub
The databinding is done like this
Public Shared Sub RetRptBySPNBOCAP(ByRef dg As GridView, ByVal dataTable As DataTable)
dg.DataSource = dataTable
dg.DataBind()
End Sub
Then in preparation for the datatables to be sent to an Excel file the data in ViewState is set to a DataTable like this, but the dataTable.Rows.Count() is throwing a NullReferenceException error as though the databind isn't taking place?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cellDate As DateTime = DateTime.MinValue
Dim dataTable As DataTable = Nothing
Dim prefix As String = "Pati_NBOCAP"
Select Case (Request.QueryString("type").ToString)
Case "Pati"
dataTable = ViewState("patiDataTable")
Case "Tum"
dataTable = ViewState("tumDataTable")
prefix = "Tum_NBOCAP"
Case "Che"
dataTable = ViewState("cheDataTable")
prefix = "Che_NBOCAP"
Case "Path"
dataTable = ViewState("pathDataTable")
prefix = "Path_NBOCAP"
Case "Sur"
dataTable = ViewState("surDataTable")
prefix = "Sur_NBOCAP"
End Select
RetRptBySPNBOCAP(Results, dataTable)
Dim rCount As Integer
If dataTable.Rows.Count() > 0 Then
rCount = dataTable.Rows.Count()
End If
End Sub
You must know that viewstate is a per page concept. So if you put data in the viewstate of a particular page you can't retrieve them from another page. Instead of viewstate you can use Session which is the same for all the pages executed within a user session.
Session("patiDataTable") = patiDataTable
Also, viewstate is by default stored client side ans thus is not suitable for large data objects such as datatables.

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.

Accessing multiple dynamic controls values

I am adding multiple controls dynamically based on a dropdownlist that the user selects. i.e. if the user selects 3 then 3 sets of the controls are added. My problem is not in adding the controls, I can add them fine, I haven't added all my code but the main parts to understand what I am doing.
Once the controls have been created, the relevant info is captured. On the Update click I need to access the values of these dynamic controls by looping through in the correct order and retrieve the values and write to the database. I can't seem to access them correctly.
Hopefully I am making sense. Any help would be appreciated. Thanks
''Loop through first set of controls and get values and then the next set etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
Below is my Code:
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RecreateControlsTxt("txt", "TextBox")
RecreateControlsChart("comboChart", "RadComboBox")
RecreateControls("combo", "RadComboBox")
RecreateControlsCP("cp", "RadColorPicker")
End Sub
Protected Sub AddControls_Click(sender As Object, e As EventArgs) Handles AddControls.Click
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateTextbox("txt-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboChart("comboChart-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboField("combo-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateColourPicker("cp-" & Convert.ToString(i + 1))
Next
End Sub
Private Sub CreateTextbox(ByVal ID As String)
Dim txt As New TextBox()
txt.ID = ID
txt.Height = 20
Me.divDesc.Controls.Add(txt)
End Sub
Private Sub CreateComboField(ByVal ID As String)
Dim combo As New RadComboBox()
combo.ID = ID
combo.DataSource = Me.odsChartsSeriesField
combo.DataTextField = "FieldNames"
combo.DataValueField = "FieldNames"
combo.DataBind()
Me.divField.Controls.Add(combo)
End Sub
Private Sub CreateComboChart(ByVal ID As String)
Dim comboChart As New RadComboBox()
comboChart.ID = ID
Dim item1 As New RadComboBoxItem()
item1.Text = "Line"
item1.Value = "smoothedLine"
item1.ImageUrl = ("Images/linechart.png")
comboChart.Items.Add(item1)
Dim item2 As New RadComboBoxItem()
item2.Text = "Column"
item2.Value = "column"
item2.ImageUrl = ("Images/bar chart.png")
comboChart.Items.Add(item2)
Dim item3 As New RadComboBoxItem()
item3.Text = "Pie"
item3.Value = "pie"
item3.ImageUrl = ("Images/pie chart.jpg")
comboChart.Items.Add(item3)
Me.divChart.Controls.Add(comboChart)
End Sub
Private Sub CreateColourPicker(ByVal ID As String)
Dim cp As New RadColorPicker()
cp.ID = ID
cp.ShowIcon = True
cp.Style("padding-top") = "1px"
cp.CssClass = "CustomHeight"
Me.divCol.Controls.Add(cp)
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
Dim alltxt = divDesc.Controls.OfType(Of TextBox)()
Dim allcomboChart = divChart.Controls.OfType(Of RadComboBox)()
Dim allcomboField = divField.Controls.OfType(Of RadComboBox)()
Dim allcp = divCol.Controls.OfType(Of RadColorPicker)()
''Loop through first set of controls and get values and then the next etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub
You have a repeated set of controls. Therefore you need a corresponding repeated set of variables that store these values.
I suggest creating a class where you can store a variable (or property) set.
Public Class ControlSet
Public Property Description As String
Public Property Type As String
Public Property XFieldName As String
Public Property Colour As String
End Class
Create an array that holds these values
Dim Values = New ControlSet(ddlFieldNames.SelectedIndex) {}
And retrieve the values in a loop
For i As Integer = 0 To Values.Length - 1
Values(i).Description = CType(divDesc.FindControl("txt-" & Convert.ToString(i + 1)), TextBox).Text
Values(i).Type = CType(divChart.FindControl("comboChart-" & Convert.ToString(i + 1)), RadComboBox).SelectedValue
Values(i).XFieldName = ...
...
Next
Also use the ID of the control; this helps to avoid confusion in case you have several controls of the same type.
you can use .FindControl(string id) method, and you should keep the controls count in your view state or session:
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
''Loop through first set of controls and get values and then the next etc..
For i As Integer = 0 To controlsCount - 1
Dim Description as string = ((TextBox)divDesc.FindControl("txt-" & Convert.ToString(i + 1))).Text ''Get Textbox value
Dim Type as string = ((RadComboBox)divChart.FindControl("comboChart-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim XFieldName as string = ((RadComboBox)divField.FindControl("combo-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim Colour as string = ((RadColorPicker)divField.FindControl("cp-" & Convert.ToString(i + 1))).SelectedValue ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
Next
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub

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