OnSelectedIndexChanged not working first selection, but will on subsequent selections - asp.net

I have a listbox in a datagrid that is supposed to update upon selection change, and it does, but not on first try. only after it has posted back, after the first time it is clicked will it work as intended. any help appreciated.
Here is the front end portion of the datagrid with the listbox.
<asp:TemplateColumn HeaderText="Qty">
<ItemStyle HorizontalAlign="Center" Wrap="False" CssClass="grid" />
<HeaderStyle HorizontalAlign="Center" ForeColor="Black" Font-Bold="true" CssClass="grid" width="30" />
<ItemTemplate>
<asp:ListBox ID="lstQty" rows="1" runat="server" AutoPostBack="True" EnableViewState="True" OnSelectedIndexChanged="lstQtyUpdate" />
</ItemTemplate>
</asp:TemplateColumn>
Here is the page load section:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
LoadCart()
cartList.Columns(0).Visible = False
If (cartList.Items.Count = 0) Then
cartList.Visible = False
lblEmptyMsg.Visible = True
Else
cartList.Visible = True
lblEmptyMsg.Visible = False
End If
End If
Catch ex As Exception
Errorlog(ex, "Cart.Page_Load()")
End Try
End Sub
This is the sub that is called with the onselectedindexchanged:
Protected Sub lstQtyUpdate(sender As Object, e As System.EventArgs)
Dim lb As New ListBox
lb = CType(sender, ListBox)
Dim thisID As String = lb.ClientID
Dim oiQty As Integer = ComFunctions.ConvertToInt(lb.SelectedItem.Value)
Dim oiID As Integer = 0
For Each item As DataGridItem In cartList.Items
lb = CType(item.FindControl("lstQty"), ListBox)
If (thisID = lb.ClientID) Then
oiID = ComFunctions.ConvertToInt(item.Cells(0).Text)
Exit For
End If
Next.....
Here is the binding for the datagrid, which may be the culprit.
Private Sub cartList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles cartList.ItemDataBound
Try
Dim rbd As ImageButton
Dim lst As ListBox
Dim id As Integer = 0
Dim evTitle As String = String.Empty
Dim evImage As String = String.Empty
Dim capacity As Integer = 0
Dim soldseats As Integer = 0
Dim seatsleft As Integer = 0
Dim evdate As String = String.Empty
Dim evtimestart As String = String.Empty
Dim evtimeend As String = String.Empty
Dim EditLink As String = String.Empty
Dim DeletedLink As String = String.Empty
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
id = DataBinder.Eval(e.Item.DataItem, "oi_id")
evTitle = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "title"))
evImage = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "image"))
evdate = ComFunctions.ConvertToDate(DataBinder.Eval(e.Item.DataItem, "eventsdatestart"))
capacity = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "capacity"))
seatsleft = (capacity - soldseats)
evtimestart = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdatestart")))
evtimeend = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdateend")))
Dim obj_DATA_Capacity As New DATA_Events()
soldseats = obj_DATA_Capacity.GetSeatsSold(id)
e.Item.Cells(0).Text = id
e.Item.Cells(1).Text = evTitle & "<br />" & evdate & " " & evtimestart & " - " & evtimeend
e.Item.Cells(2).Text = "<img src=""" & AppSettings("Events_ImagePath") & "/Thumb/" & evImage & """ width=""100"" />"
e.Item.Cells(3).Text = "$" & ComFunctions.ConvertToDecimal(DataBinder.Eval(e.Item.DataItem, "oi_price"), 2)
lst = CType(e.Item.FindControl("lstQty"), ListBox)
If seatsleft > 0 Then
'lst.Items.Add(0)
For I = 1 To seatsleft
lst.Items.Add(I)
Next
End If
lst.ID = id
lst.SelectedValue = ComFunctions.ConvertToInt(DataBinder.Eval(e.Item.DataItem, "oi_qty"))
rbd = CType(e.Item.FindControl("DeleteThis"), ImageButton)
rbd.CommandArgument = id
End If
Catch ex As Exception
Errorlog(ex, "quickCart.cartList_ItemDataBound()")
End Try
End Sub

I'm not sure why it does not work the first time, by the way, what does "not work" actually mean? But apart from that, your way to get the text of the first cell in the current DataGridItem is odd.
This is much more directly:
Dim lb = DirectCast(sender, ListBox)
Dim item = DirectCast(lb.NamingContainer, DataGridItem)
Dim oiID = Int32.Parse(item.Cells(0).Text)
Maybe it helps also get it working.

Related

Unable to cast object of type 'System.Web.UI.WebControls.CommandEventArgs' to type 'System.Web.UI.WebControls.DataListCommandEventArgs'

So I'm writing a small VB webform that will allow users to look up data in a MySQL DB utilizing a DataList with ItemTemplate and edit that data using the EditItemTemplate.
I've got everything working except the Update portion of the app. When the user goes to update the edits they've made, they are greeted with
Unable to cast object of type 'System.Web.UI.WebControls.CommandEventArgs' to type 'System.Web.UI.WebControls.DataListCommandEventArgs'.
I believe this is due to the linkbutton having the OnCommand= attribute set. I recived this exact error when trying to setup the Cancel command, and what I did was change
Protected Sub DataList1_CancelCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
to
Protected Sub DataList1_CancelCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
However, I cannot do the same with the update command as it is getting the edit fields from the EditItemTemplate which needs the DataListCommandEventArgs to be set.
Below is my code; I need a way around this error with my update command functioning. Any help would be awesome!
ASPx Page
<form id="SearchForm" runat="server">
<asp:SqlDataSource
ID='FarmStandSource' runat='server'
ConnectionString='<%$ ConnectionStrings:FSDATA3ConnectionString %>'
SelectCommand='SelectFarmStand'
SelectCommandType='StoredProcedure'>
</asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" ItemStyle-Width="95%" RepeatLayout="Flow"
OnEditCommand="DataList1_EditCommand"
OnCancelCommand="DataList1_CancelCommand"
OnUpdateCommand="DataList1_UpdateCommand" DataKeyField="PKF">
<ItemTemplate>
...Fields...
</ItemTemplate>
<EditItemTemplate>
...Fields...
</EditItemTemplate>
</DataList>
</form>
CODE BEHIND VB
Protected Sub DataList1_UpdateCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs)
Dim PKF As Int32 = Convert.ToInt32(DataList1.DataKeys(e.Item.ItemIndex))
Dim FarmBusinessName As TextBox = e.Item.FindControl("FarmBusinessNameEdit")
Dim FarmOwners As TextBox = e.Item.FindControl("FarmOwnersEdit")
Dim FullFarmAddress As TextBox = e.Item.FindControl("FullFarmAddressEdit")
Dim Address1 As TextBox = e.Item.FindControl("Address1Edit")
Dim City As TextBox = e.Item.FindControl("CityEdit")
Dim State As TextBox = e.Item.FindControl("StateEdit")
Dim Zip As TextBox = e.Item.FindControl("ZipEdit")
Dim County As TextBox = e.Item.FindControl("CountyEdit")
Dim Phone As TextBox = e.Item.FindControl("PhoneEdit")
Dim Website As TextBox = e.Item.FindControl("WebsiteEdit")
Dim Email As TextBox = e.Item.FindControl("EmailEdit")
Dim DatesOpen As TextBox = e.Item.FindControl("DatesOpenEdit")
Dim DatesClosed As TextBox = e.Item.FindControl("DatesClosedEdit")
Dim StandOpenTime As TextBox = e.Item.FindControl("StandOpenTimeEdit")
Dim StandCloseTime As TextBox = e.Item.FindControl("StandCloseTimeEdit")
Dim BIO As TextBox = e.Item.FindControl("BIOEdit")
Dim OpenEndedResponse As TextBox = e.Item.FindControl("OpenEndedResponseEdit")
Dim Vegetables As CheckBox = e.Item.FindControl("VegetablesEdit")
Dim Grains As CheckBox = e.Item.FindControl("GrainsEdit")
Dim BreadBakedGoods As CheckBox = e.Item.FindControl("BreadBakedGoodsEdit")
Dim Eggs As CheckBox = e.Item.FindControl("EggsEdit")
Dim MilksRawMilk As CheckBox = e.Item.FindControl("MilksRawMilkEdit")
Dim Cheese As CheckBox = e.Item.FindControl("CheeseEdit")
Dim CiderApples As CheckBox = e.Item.FindControl("CiderApplesEdit")
Dim Honey As CheckBox = e.Item.FindControl("HoneyEdit")
Dim WineHardCider As CheckBox = e.Item.FindControl("WineHardCiderEdit")
Dim Fruits As CheckBox = e.Item.FindControl("FruitsEdit")
Dim Berries As CheckBox = e.Item.FindControl("BerriesEdit")
Dim Maples As CheckBox = e.Item.FindControl("MaplesEdit")
Dim Chicken As CheckBox = e.Item.FindControl("ChickenEdit")
Dim Turkey As CheckBox = e.Item.FindControl("TurkeyEdit")
Dim Beef As CheckBox = e.Item.FindControl("BeefEdit")
Dim Pork As CheckBox = e.Item.FindControl("PorkEdit")
Dim Lamb As CheckBox = e.Item.FindControl("LambEdit")
Dim Goat As CheckBox = e.Item.FindControl("GoatEdit")
Dim WoolFiber As CheckBox = e.Item.FindControl("WoolFiberEdit")
Dim WoodProducts As CheckBox = e.Item.FindControl("WoodProductsEdit")
Dim Flowers As CheckBox = e.Item.FindControl("FlowersEdit")
Dim CannedBottledGoods As CheckBox = e.Item.FindControl("CannedBottledGoodsEdit")
Dim PlantSeedlingsStarts As CheckBox = e.Item.FindControl("PlantSeedlingsStartsEdit")
Dim PlantsTrees As CheckBox = e.Item.FindControl("PlantsTreesEdit")
Dim Other As TextBox = e.Item.FindControl("OtherEdit")
Dim CertifiedOrganic As TextBox = e.Item.FindControl("CertifiedOrganicEdit")
Dim OrganicCertifier As TextBox = e.Item.FindControl("OrganicCertifierEdit")
Dim OtherFarmsLocal As TextBox = e.Item.FindControl("OtherFarmsLocalEdit")
Dim SupplementalCatagories As TextBox = e.Item.FindControl("SupplementalCatagoriesEdit")
Dim BeginOperation As TextBox = e.Item.FindControl("BeginOperationEdit")
Dim PickYourOwn As CheckBox = e.Item.FindControl("PickYourOwnEdit")
Dim EBT As CheckBox = e.Item.FindControl("EBTEdit")
Dim Staffed As TextBox = e.Item.FindControl("StaffedEdit")
Dim CustomersPeakSeason As TextBox = e.Item.FindControl("CustomersPeakSeasonEdit")
Dim Customers2015 As TextBox = e.Item.FindControl("Customers2015Edit")
Dim Customers2014 As TextBox = e.Item.FindControl("Customers2014Edit")
Dim PercentSelfProduced As TextBox = e.Item.FindControl("PercentSelfProducedEdit")
Dim SellOtherFarms As CheckBox = e.Item.FindControl("SellOtherFarmsEdit")
Dim LiabilityInsurance As CheckBox = e.Item.FindControl("LiabilityInsuranceEdit")
Dim FarmBusinessNameValue = ""
If FarmBusinessName.Text.Trim().Length > 0 Then
FarmBusinessNameValue = FarmBusinessName.Text.Trim()
End If
Dim FarmOwnersValue = ""
If FarmOwners.Text.Trim().Length > 0 Then
FarmOwnersValue = FarmOwners.Text.Trim()
End If
Dim FullFarmAddressValue = ""
If FullFarmAddress.Text.Trim().Length > 0 Then
FullFarmAddressValue = FullFarmAddress.Text.Trim()
End If
Dim Address1Value = ""
If Address1.Text.Trim().Length > 0 Then
Address1Value = Address1.Text.Trim()
End If
Dim CityValue = ""
If City.Text.Trim().Length > 0 Then
CityValue = City.Text.Trim()
End If
Dim StateValue = ""
If State.Text.Trim().Length > 0 Then
StateValue = State.Text.Trim()
End If
Dim ZipValue = ""
If Zip.Text.Trim().Length > 0 Then
ZipValue = Zip.Text.Trim()
End If
Dim CountyValue = ""
If County.Text.Trim().Length > 0 Then
CountyValue = County.Text.Trim()
End If
Dim PhoneValue = ""
If Phone.Text.Trim().Length > 0 Then
PhoneValue = Phone.Text.Trim()
End If
Dim WebsiteValue = ""
If Website.Text.Trim().Length > 0 Then
WebsiteValue = Website.Text.Trim()
End If
Dim EmailValue = ""
If Email.Text.Trim().Length > 0 Then
EmailValue = Email.Text.Trim()
End If
Dim DatesOpenValue = ""
If DatesOpen.Text.Trim().Length > 0 Then
DatesOpenValue = DatesOpen.Text.Trim()
End If
Dim DatesClosedValue = ""
If DatesClosed.Text.Trim().Length > 0 Then
DatesClosedValue = DatesClosed.Text.Trim()
End If
Dim StandOpenTimeValue = ""
If StandOpenTime.Text.Trim().Length > 0 Then
StandOpenTimeValue = StandOpenTime.Text.Trim()
End If
Dim StandCloseTimeValue = ""
If StandCloseTime.Text.Trim().Length > 0 Then
StandCloseTimeValue = StandCloseTime.Text.Trim()
End If
Dim BIOValue = ""
If BIO.Text.Trim().Length > 0 Then
BIOValue = BIO.Text.Trim()
End If
Dim OpenEndedResponseValue = ""
If OpenEndedResponse.Text.Trim().Length > 0 Then
OpenEndedResponseValue = OpenEndedResponse.Text.Trim()
End If
Dim VegetablesValue = ""
If Vegetables.Checked <> "" Then
VegetablesValue = Vegetables.Checked
End If
Dim GrainsValue = ""
If Grains.Checked <> "" Then
GrainsValue = Grains.Checked
End If
Dim BreadBakedGoodsValue = ""
If BreadBakedGoods.Checked <> "" Then
BreadBakedGoodsValue = BreadBakedGoods.Checked
End If
Dim EggsValue = ""
If Eggs.Checked <> "" Then
EggsValue = Eggs.Checked
End If
Dim MilksRawMilkValue = ""
If MilksRawMilk.Checked <> "" Then
MilksRawMilkValue = MilksRawMilk.Checked
End If
Dim CheeseValue = ""
If Cheese.Checked <> "" Then
CheeseValue = Cheese.Checked
End If
Dim CiderApplesValue = ""
If CiderApples.Checked <> "" Then
CiderApplesValue = CiderApples.Checked
End If
Dim HoneyValue = ""
If Honey.Checked <> "" Then
HoneyValue = Honey.Checked
End If
Dim WineHardCiderValue = ""
If WineHardCider.Checked <> "" Then
WineHardCiderValue = WineHardCider.Checked
End If
Dim FruitsValue = ""
If Fruits.Checked <> "" Then
FruitsValue = Fruits.Checked
End If
Dim BerriesValue = ""
If Berries.Checked <> "" Then
BerriesValue = Berries.Checked
End If
Dim MaplesValue = ""
If Maples.Checked <> "" Then
MaplesValue = Maples.Checked
End If
Dim ChickenValue = ""
If Chicken.Checked <> "" Then
ChickenValue = Chicken.Checked
End If
Dim TurkeyValue = ""
If Turkey.Checked <> "" Then
TurkeyValue = Turkey.Checked
End If
Dim BeefValue = ""
If Beef.Checked <> "" Then
BeefValue = Beef.Checked
End If
Dim PorkValue = ""
If Pork.Checked <> "" Then
PorkValue = Pork.Checked
End If
Dim LambValue = ""
If Lamb.Checked <> "" Then
LambValue = Lamb.Checked
End If
Dim GoatValue = ""
If Goat.Checked <> "" Then
GoatValue = Goat.Checked
End If
Dim WoolFiberValue = ""
If WoolFiber.Checked <> "" Then
WoolFiberValue = WoolFiber.Checked
End If
Dim WoodProductsValue = ""
If WoodProducts.Checked <> "" Then
WoodProductsValue = WoodProducts.Checked
End If
Dim FlowersValue = ""
If Flowers.Checked <> "" Then
FlowersValue = Flowers.Checked
End If
Dim CannedBottledGoodsValue = ""
If CannedBottledGoods.Checked <> "" Then
CannedBottledGoodsValue = CannedBottledGoods.Checked
End If
Dim PlantSeedlingsStartsValue = ""
If PlantSeedlingsStarts.Checked <> "" Then
PlantSeedlingsStartsValue = PlantSeedlingsStarts.Checked
End If
Dim PlantsTreesValue = ""
If PlantsTrees.Checked <> "" Then
PlantsTreesValue = PlantsTrees.Checked
End If
Dim OtherValue = ""
If Other.Text.Trim().Length > 0 Then
OtherValue = Other.Text.Trim()
End If
Dim CertifiedOrganicValue = ""
If CertifiedOrganic.Text.Trim().Length > 0 Then
CertifiedOrganicValue = CertifiedOrganic.Text.Trim()
End If
Dim OrganicCertifierValue = ""
If OrganicCertifier.Text.Trim().Length > 0 Then
OrganicCertifierValue = OrganicCertifier.Text.Trim()
End If
Dim OtherFarmsLocalValue = ""
If OtherFarmsLocal.Text.Trim().Length > 0 Then
OtherFarmsLocalValue = OtherFarmsLocal.Text.Trim()
End If
Dim SupplementalCatagoriesValue = ""
If SupplementalCatagories.Text.Trim().Length > 0 Then
SupplementalCatagoriesValue = SupplementalCatagories.Text.Trim()
End If
Dim BeginOperationValue = ""
If BeginOperation.Text.Trim().Length > 0 Then
BeginOperationValue = BeginOperation.Text.Trim()
End If
Dim PickYuorOwnValue = ""
If PickYourOwn.Checked <> "" Then
PickYuorOwnValue = PickYourOwn.Checked
End If
Dim EBTValue = ""
If EBT.Checked <> "" Then
EBTValue = EBT.Checked
End If
Dim StaffedValue = ""
If Staffed.Text.Trim().Length > 0 Then
StaffedValue = Staffed.Text.Trim()
End If
Dim CustomersPeakSeasonValue = ""
If CustomersPeakSeason.Text.Trim().Length > 0 Then
CustomersPeakSeasonValue = CustomersPeakSeason.Text.Trim()
End If
Dim Customers2015Value = ""
If Customers2015.Text.Trim().Length > 0 Then
Customers2015Value = Customers2015.Text.Trim()
End If
Dim Customers2014Value = ""
If Customers2014.Text.Trim().Length > 0 Then
Customers2014Value = Customers2014.Text.Trim()
End If
Dim PercentSelfProducedValue = ""
If PercentSelfProduced.Text.Trim().Length > 0 Then
PercentSelfProducedValue = PercentSelfProduced.Text.Trim()
End If
Dim SellOtherFarmsValue = ""
If SellOtherFarms.Checked <> "" Then
SellOtherFarmsValue = SellOtherFarms.Checked
End If
Dim LiabilityInsuranceValue = ""
If LiabilityInsurance.Checked <> "" Then
LiabilityInsuranceValue = LiabilityInsurance.Checked
End If
Dim sqlConnection3 As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("FSDATA").ConnectionString)
Dim cmd As New SqlCommand
cmd.CommandText = "UpdateFarmStand"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection3
sqlConnection3.Open()
cmd.ExecuteNonQuery()
sqlConnection3.Close()
DataList1.EditItemIndex = -1
hiddenindexfield.Text = ""
DataList1.DataBind()
SearchPanel.Visible = "True"
End Sub
UPDATE: I noticed that the UpdateCommand isn't firing at all, so I used codebreaks to find specifically where it was failing. Turns out it's dropping when it reaches the nested IF statement in my PostBack Checker in the Page_Load Handler. This checks to see if the user was in the edit view after PostBack, then does something based on that. Cutting off the IF statement and just letting the Page_Load handle the select statement throws a postback error.
Page_Load Handler
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim sqlConnection1 As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("FSDATA").ConnectionString)
Dim cmd As New SqlCommand
cmd.CommandText = "SelectFarmStand"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
Dim dt As New DataTable
Dim retData As New SqlDataAdapter
If Not IsPostBack Then
retData.SelectCommand = cmd
retData.Fill(dt)
DataList1.DataSource = dt
DataList1.DataBind()
Else
If hiddenindexfield.Text <> "" Then
DataList1.EditItemIndex = Convert.ToInt32(hiddenindexfield.Text)
DisplayPanel.Visible = True '<- FAILS HERE
Else
retData.SelectCommand = cmd
retData.Fill(dt)
DataList1.DataSource = dt
DataList1.DataBind()
End If
End If
End Sub
DataListCommandEventArgs is derived from CommandEventArgs. So if the event arg was of the correct subtype it should cast. I think problem is you are trying to use the same handler for different types of events. (I didn't see the handler for the Link button you mentioned).
You can do that, but then you have to test the argument subtype. One way to do that is with the TryCast operator. For example:
Sub CommandEventHandler(sender as Object, e as CommandEventArgs)
Dim e1 as DataListCommandEventArgs = TryCast(e, DataListCommandEventArgs)
If e1 IsNot Nothing Then
DataListEventAHander(sender, e1)
Return
End if
' Repeat for other subtypes as needed.
End Sub
Sub DataListEventHandler(sender as Object, e as DataListCommandEventArgs)
' Your code for DataListEvents
End Sub
If your handlers are wired up correctly you should be able dispatch directly
to the correct handler, either in the mark up or with the handles clause
in the code.
Sub EventSubTypeHander(sender as Object, e as EventSubTypeArgs) handles object.EventSubType
' Event specific code here.
End Sub

Dropdownlist in gridview reset to Default Instead of selected value

I have two GridView(SalesGView and ProdGView). SalesGView contains dropdowlist and textboxes.ProdGView is wrapped with ModalPopup and is populated by dropdownlist selection from ProdGView.
The issue is when i click button select on ProdGView, the dropdownlist in the SalesGView resets to default value (Electronics) instead of selected value.
I need help on how to correct this issue.
aspx code:
SalesGView Dropdownlist
<asp:DropDownList ID="CatCode" OnSelectedIndexChanged ="CatCode_SelectedIndexChanged" AutoPostBack="true" runat="server" />
ProdGView SelectRow
<asp:GridView ID="ProdGView" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" Text="Select" runat="server" OnClick="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
Private Sub SalesGView_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles SalesGView.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ctrl As Control = e.Row.FindControl("CatCode")
If (Not (ctrl) Is Nothing) Then
Dim dd As DropDownList = CType(ctrl, DropDownList)
Dim connStr As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim sqlda As SqlDataAdapter = New SqlDataAdapter
Dim com As SqlCommand = New SqlCommand
Dim dt As DataTable
Dim conn As SqlConnection = New SqlConnection(connStr)
dt = New DataTable
com.Connection = conn
com.CommandText = "SELECT CatName FROM Prod_Category"
sqlda = New SqlDataAdapter(com)
sqlda.Fill(dt)
dd.DataTextField = "CatName"
dd.DataValueField = "CatName"
dd.DataSource = dt
dd.DataBind()
End If
End If
Dim lb As DropDownList = TryCast(e.Row.FindControl("CatCode"), DropDownList)
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(lb)
End Sub
Protected Sub CatCode_SelectedIndexChanged(sender As Object, e As EventArgs)
Me.ModalPopupExtender1.Show()
BindProdGrid()
End Sub
Protected Sub SelectRow(sender As Object, e As EventArgs)
Dim dt As New DataTable()
If ViewState("DataTable") Is Nothing Then
dt = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Column2"), New DataColumn("Column4", GetType(String))})
Else
dt = DirectCast(ViewState("DataTable"), DataTable)
End If
Dim row As GridViewRow = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow)
Dim desc As String = row.Cells(2).Text
Dim price As String = row.Cells(3).Text
dt.Rows.Add(desc, price)
Me.SalesGView.DataSource = dt
Me.SalesGView.DataBind()
ViewState("DataTable") = dt
End Sub
Private Sub BindProdGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim rowIndex As Integer = 0
Dim catname As DropDownList = CType(SalesGView.Rows(rowIndex).Cells(1).FindControl("CatCode"), DropDownList)
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand("select Product.CatID,Product.PName,Product.PDesc, " _
& " Product_Details.USP, Prod_Category.CatName " _
& " from Product inner join Product_Details on Product.CatID= Product_Details.CatID " _
& " inner join Prod_Category on Product_Details.CatID=Prod_Category.CatID where Prod_Category.CatName='" & (catname.SelectedItem.Text) & "' ")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Dim dt As New DataTable()
sda.Fill(dt)
Me.ProdGView.DataSource = dt
Me.ProdGView.DataBind()
End Using
End Using
End Using
End Sub

Get all selected values of CheckBoxList in VB.NET

I've used ASP's CheckBoxList control. Now what I want is to get the all selected values in VB code.
HTML
<asp:CheckBoxList ID="chkbxlst_Users" runat="server" RepeatColumns="2" RepeatDirection="Vertical" RepeatLayout="Table"></asp:CheckBoxList>
VB
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim eStr As String = String.Empty
Try
Catch ex As Exception
Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
On this Save button's click I want to get all the selected items' value and text in dataset.
try this..
For Each li As ListItem In chkbxlst_Users.Items
If li.Selected Then
// add item data into your dataset
Else
// do whatever you need
End If
End If
Next
You can try following code:
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim dt = New DataTable()
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcName)
Dim eStr As String = String.Empty
Try
For Each checkBox As CheckBox In chkbxlst_Users.Items
If (checkBox.Checked = True) Then
Dim dr As DataRow = dt.NewRow()
dr("ID") = checkBox.Text
dt.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt)
Catch ex As Exception
'Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
Try this code
Dim ds_selectedProjects As New DataSet
Dim dt_selectedProjects As New DataTable
dt_selectedProjects.Columns.Add("Value")
dt_selectedProjects.Columns.Add("Text")
Dim dr As DataRow
For i = 0 To chkbxlst_Users.Items.Count - 1
If chkbxlst_Users.Items(i).Selected Then
dr = dt_selectedProjects.NewRow()
dr("Value") = Val(chkbxlst_Users.Items(i).Value)
dr("Text") = chkbxlst_Users.Items(i).Text
dt_selectedProjects.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt_selectedProjects)
Try this
Dim str As [String] = ""
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
If str = "" Then
str = "'" + CheckBoxList1.Items(i).Value + "'"
Else
str += "," + "'" + CheckBoxList1.Items(i).Value + "'"
End If
End If
Next
'display in a textbox or lable with ID txtmsg
txtmsg.Text = str

Integer column in GridView is being sorted as a string

I have a GridView, which has a column as shown below:
<asp:TemplateField HeaderText="Vendor Path" SortExpression="DocumentTemplateFieldID" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="vendor" Height="10px" Width="60px" runat="server" Text='<%# Eval("DocumentTemplateFieldID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
I allow sorting; however, it sorts it as if it were a string. In the database, it is an integer column.
How do I make my GridView accept that I'm really putting integers in there? I tried to convert it and that didn't work.
Code added:
Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles GridView1.Sorting
dsData = Session("dataTableView")
Dim sortExpression As String = e.SortExpression
Dim direction As String = String.Empty
If SortDirection = SortDirection.Ascending Then
SortDirection = SortDirection.Descending
direction = " DESC"
Else
SortDirection = SortDirection.Ascending
direction = " ASC"
End If
Dim table As DataTable = dsData
table.DefaultView.Sort = sortExpression + direction
GridView1.DataSource = table
GridView1.DataBind()
Session("dataTableView") = table
End Sub
Private Property SortDirection() As SortDirection
Get
If Session("sortDir") = Nothing Then
Session("sortDir") = SortDirection.Ascending
End If
Return CType(Session("sortDir"), SortDirection)
End Get
Set(ByVal value As SortDirection)
Session("sortDir") = value
End Set
End Property
Updated:
Public Function initialQuery(ByVal vendorID As String) As DataTable
Dim objConn As IDbConnection = Nothing
Dim dsData As New DataTable
Dim objParams(0) As IDbDataParameter
Try
objConn = DBAccess.GetConnection
objParams(0) = DBAccess.CreateParameter("DWSVendorID", DbType.String, vendorID, ParameterDirection.Input)
'Need to figure out how to add the below code:
If (Not IsNothing(vendorID) And Not vendorID = 0) Then
' strBlder.Append("WHERE B.DocumentProviderID = '" + vendorID.ToString + "' ")
End If
dsData = DBAccess.ExecuteDataTable(objConn, DataAccessHelper.Schema & "LLC.[DWSMappingToolInitialQuery]", objParams)
Finally
If Not objConn Is Nothing Then
DBAccess.CloseConnection(objConn)
End If
End Try
If dsData.Rows.Count > 0 Then
Return dsData
End If
Return Nothing
End Function

ASP.net Dropdowlist added in runtime - event handler not getting fired

THis event does not get fired - not sure why
Protected Sub ddl_selectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim a As String = ""
'this does not get fired
End Sub
<asp:GridView ID="GridViewAssignment" runat="server" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None"
Width="100%">
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#86A4CA" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#808080" Font-Bold="True" ForeColor="#E7E7FF" />
</asp:GridView>
Protected Sub GridViewAssignment_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewAssignment.RowDataBound
Dim dateApplicationCreatedCell As TableCell = e.Row.Cells(0) 'app created on
Dim typeOfReview As TableCell = e.Row.Cells(7) 'type
Dim QCCell As TableCell = e.Row.Cells(8) 'qc
Dim dateReviewAssignedCell As TableCell = e.Row.Cells(9) 'date assigned
Dim reviewerNameCell As TableCell = e.Row.Cells(10) 'reviewer
Dim dateReviewCompletedCell As TableCell = e.Row.Cells(11) 'date completed review
Dim ddl As DropDownList
If e.Row.RowIndex <> -1 Then
If dateReviewAssignedCell.Text.Trim = " " Then
dateReviewAssignedCell.Text = Now.Date
End If
Dim sqlCondition As String = String.Empty
If dateReviewCompletedCell.Text.Trim = " " Then
Dim nameToSelect As String
If reviewerNameCell.Text.Trim <> " " Then
Dim dateReviewAssigned As Date = dateReviewAssignedCell.Text
Dim elapsedSinceAssigned As Long = DateDiff(DateInterval.Day, dateReviewAssigned.Date, Now.Date, Microsoft.VisualBasic.FirstDayOfWeek.Monday, FirstWeekOfYear.Jan1)
If elapsedSinceAssigned <= 3 Then
dateReviewAssignedCell.BackColor = Drawing.Color.LightGreen
ElseIf elapsedSinceAssigned > 3 And elapsedSinceAssigned <= 5 Then
dateReviewAssignedCell.BackColor = Drawing.Color.Yellow
ElseIf elapsedSinceAssigned > 5 Then
dateReviewAssignedCell.BackColor = Drawing.Color.OrangeRed
End If
nameToSelect = reviewerNameCell.Text.Trim
Else
nameToSelect = String.Empty
End If
If QCCell.Text.ToLower.Contains("qc") Then
If typeOfReview.Text.ToLower.Contains("bca") Then
sqlCondition = "where [QCRole_Level1] = 1 and [BCA] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("ehp") Then
sqlCondition = "where [QCRole_Level1] = 1 and [EHP] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("eligibility") Then
sqlCondition = "where [QCRole_Level1] = 1 and [ProgramEligibility] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("engineering") Then
sqlCondition = "where [QCRole_Level1] = 1 and [Engineering] = 1"
End If
ElseIf QCCell.Text.ToLower.Contains("initial") Then
If typeOfReview.Text.ToLower.Contains("bca") Then
sqlCondition = "where [BCA] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("ehp") Then
sqlCondition = "where [EHP] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("eligibility") Then
sqlCondition = "where [ProgramEligibility] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("engineering") Then
sqlCondition = "where [Engineering] = 1"
End If
ElseIf QCCell.Text.ToLower.Contains("letter") Then
sqlCondition = "where [FinalLetter] = 1"
End If
ddl = New DropDownList
ddl.EnableViewState = True
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf ddl_selectedIndexChanged
ddl.Width = New Unit(110, UnitType.Pixel)
dropDownListSelect(ddl, nameToSelect, sqlCondition)
reviewerNameCell.Controls.Add(ddl)
End If
End If
End Sub
Protected Sub GridViewAssignment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridViewAssignment.SelectedIndexChanged
End Sub
Protected Sub dropDownListSelect(ByVal ddlist As DropDownList, ByVal valueToSelect As String, ByVal sqlFilterString As String)
Dim sqlQuery As String = "SELECT [ReviewerName],[Specialty],[Tiger],[Triage]" + _
",[ProgramEligibility],[Engineering],[BCA],[EHP],[QCRole_Level1],[QCRole_Overall]" + _
",[FinalLetter] FROM [SubApplicationTracker].[dbo].[ReviewerResources] " + _
sqlFilterString + " order by ReviewerName asc"
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("SubAppTrackerConnString").ConnectionString
Dim sqlconnection As SqlConnection = New SqlConnection(connStr)
sqlconnection.Open()
Dim sqlCommand As SqlCommand = New SqlCommand(sqlQuery, sqlconnection)
Dim dr As SqlDataReader = sqlCommand.ExecuteReader
ddlist.Items.Clear()
ddlist.Items.Add("")
Do While dr.Read
Dim itemToAdd As New ListItem
itemToAdd.Text = dr("ReviewerName")
itemToAdd.Value = dr("ReviewerName")
ddlist.Items.Add(itemToAdd)
Loop
'if we find no reviewer then combo should be at the blank item
If valueToSelect = String.Empty Then
ddlist.Items(0).Selected = True
Else 'if we find a matching value then combo should selected at that value
If ddlist.Items.FindByValue(valueToSelect) IsNot Nothing Then
ddlist.Items.FindByValue(valueToSelect).Selected = True
Else 'if we find a non empty value but it doesnt exist in the combo list then - add that item to combo list and select it
Dim newItem As New ListItem
newItem.Text = valueToSelect
newItem.Value = valueToSelect
ddlist.Items.Add(newItem)
ddlist.Items.FindByValue(valueToSelect).Selected = True
End If
End If
End Sub
You need to be data binding the gridview on every postback, in order to get the event to fire?

Resources