Reapeater Control button click - asp.net

When I click on the vote button the detail will insert but all the the page detail insert I want only perticular button click data should insert.
Code:
Protected Sub vote(sender As Object, e As EventArgs) {
//( lblName,lbl_id ,lbl_name,Label1 this is all reapeater field id )
Dim lblName As Label
Dim lbl_id As Label
Dim lbl_name As Label
Dim Label1 As Label
For Each item As RepeaterItem In rpt_path.Items
lblName = CType(item.FindControl("lblName"), Label)
lbl_id = CType(item.FindControl("lbl_id"), Label)
lbl_name = CType(item.FindControl("lbl_name"), Label)
Label1 = CType(item.FindControl("Label1"), Label)
con=("Connection String")
con.Open()
Dim command As New OleDbCommand("insert into CFC(C_E_No,Name,Class_id,Party_id)values(#C_E_No,#Name,#Class_id,#Party_id)", con)
command.Parameters.AddWithValue("(#C_E_No", CType(item.FindControl("lblName"), Label).Text)
command.Parameters.AddWithValue("#Name", CType(item.FindControl("lbl_id"), Label).Text)
command.Parameters.AddWithValue("#Class_id", CType(item.FindControl("lbl_name"), Label).Text)
command.Parameters.AddWithValue("#Party_id", CType(item.FindControl("Label1"), Label).Text)
command.ExecuteNonQuery()
con.Close()

Design
<asp:Label ID="lbl_iid" runat="server" Text="Label" Visible="false"></asp:Label>
</div>
<asp:Label ID="lbl_iname" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Label ID="lbl_icid" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:Label ID="lbl_ipid" runat="server" Text="Label" Visible="false"></asp:Label>
Coding on Vote Button Click
Protected Sub vote(sender As Object, e As EventArgs)
Dim str As String = CType(sender, Button).CommandArgument
Session("vid") = str
MsgBox(Session("vid"))
Connection String
cmd = New OleDbCommand("select * from candi where C_E_No='" & str.ToString() & "' ")
ds = New DataSet
cmd.Connection = con
con.Open()
da = New OleDbDataAdapter(cmd)
MsgBox(cmd.CommandText)
da.Fill(ds, "candi")
lbl_iid.Text = ds.Tables(0).Rows(0)(0)
lbl_iname.Text = ds.Tables(0).Rows(0).Item(1).ToString()
lbl_icid.Text = ds.Tables(0).Rows(0).Item(2).ToString()
lbl_ipid.Text = ds.Tables(0).Rows(0).Item(4).ToString()
con.Close()
Connection String
cmd = New OleDbCommand("insert into CFC(Stu_E_No,C_E_No,Name,Class_id,Party_id)values('" & Session("stdid") & "','" & lbl_iid.Text & "','" & lbl_iname.Text & "','" & lbl_icid.Text & "','" & lbl_ipid.Text & "') ")
MsgBox(cmd.CommandText)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Succes")

Related

How to upload xls file's data to SQL Server in devexpress popup control?

I have enquiry on how to insert xls file data into SQL Server. The upload button, and gridview control are placed inside the devexpress popup control and the code works without the popup control but doesn't work with popup control. When I inserted the xls file and clicked the upload button, the label display showed "Please select a file to upload!" although I have did this.
ASP.NET markup:
<dx:ASPxPopupControl ID="popupControl" ClientInstanceName="popupControl"
AllowDragging="true" ShowOnPageLoad="false" runat="server" AllowResize="true" >
<ContentCollection>
<dx:PopupControlContentControl runat="server">
<div class="flexs">
<dx:ASPxUploadControl ID="XXUpload" runat="server" UploadMode="Auto" ValidationSettings-AllowedFileExtensions=".xls" width="500px" >
</dx:ASPxUploadControl>
<dx:ASPxLabel ID="Label2" runat="server" Text=""></dx:ASPxLabel>
<dx:ASPxButton ID="DataUpload" runat="server" Text="UPLOAD" OnClick="DataUpload_Click ">
</dx:ASPxButton>
<dx:ASPxGridView ID="UpdateSplitGrid" ClientIDMode="Static" ClientInstanceName="UpdateSplitGrid" runat="server" Width="200%" DataSourceID="dtSource2" Theme="DevEx" >
.....
</dx:ASPxGridView>
</div>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
Vb.net code:
Function uploadExcel1(filePath As String) As String
Dim str As String = ""
Dim namestr1 As String = XXUpload.UploadedFiles.ToArray(0).FileName.ToString
If namestr1 <> "" Then
If Not XXUpload.UploadedFiles.ToArray(0).IsValid Then
str = "Fail to Upload " + namestr1
Else
XXUpload.UploadedFiles.ToArray(0).SaveAs(filePath)
str = " Successfully Uploaded!"
End If
Else
str = "Please select a File to upload!"
End If
Return str
End Function
Function getDTe(filename As String, ByVal sql As String) As DataTable
Dim dt As New DataTable()
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';"
Dim connection As New OleDbConnection(connectionString)
Dim adapter As New OleDbDataAdapter(sql, connection)
adapter.Fill(dt)
Return dt
End Function
Protected Sub DataUpload_Click(sender As Object, e As EventArgs)
Dim filepath As String = "C:\New folder\" + XXUpload.UploadedFiles.ToArray(0).FileName.ToString + ".xls"
Dim msg As String = uploadExcel1(filepath)
Label2.Text = msg
If msg.Contains("Successfully") Then
Dim sql As String = "select * from [Sheet1$]"
Dim dt As New DataTable
dt = getDTe(filepath, sql)
If dt.Rows.Count > 0 Then
Dim i As Integer = 0
Dim colname() As String = {"LotID", "Split_Cat", "Engr_Time", "PLANDESC", "STEPSEQ", "EQPTYPE", "PPID", "STEPDESC", "Split", "Recipe", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22"}
For Each dc As DataColumn In dt.Columns
If dc.ColumnName.ToString <> colname(i) Then
Label2.Text = " File is not in correct format - Details: " + dc.ColumnName.ToString
Return
End If
i = i + 1
Next
For Each dr In dt.Rows
Try
Dim LotID As String = dr("LotID").ToString
Dim Split_Cat As String = dr("Split_Cat").ToString
Dim Engr_Time As String = dr("Engr_Time").ToString
Dim PLANDESC As String = dr("PLANDESC").ToString
Dim STEPSEQ As String = dr("STEPSEQ").ToString
Dim EQPTYPE As String = dr("EQPTYPE").ToString
Dim PPID As String = dr("PPID").ToString
Dim STEPDESC As String = dr("STEPDESC").ToString
Dim Split As String = dr("Split").ToString
Dim Recipe As String = dr("Recipe").ToString
Dim a As String = dr("F11").ToString
Dim b As String = dr("F12").ToString
Dim c As String = dr("F13").ToString
.............
Dim insertsql2 As String = ""
insertsql2 += "insert into PTHOME.dbo.SplitTable (LotID,Split_Cat,Engr_Time,PLANDESC,STEPSEQ,EQPTYPE,PPID,STEPDESC,Split,Recipe,[1],[2],[3]) values "
insertsql2 += "('" + LotID + "','" + Split_Cat + "','" + Engr_Time + "','" + PLANDESC + "','" + STEPSEQ + "','" + EQPTYPE + "','" + PPID + "','" + STEPDESC + "','" + Split + "','" + Recipe + "', "
insertsql2 += " '" + a + "','" + b + "','" + c + "') "
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(insertsql2, conn)
conn.Open()
Dim res As Integer = cmd.ExecuteNonQuery
conn.Close()
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Else
Label2.Text = " NO Records Uploaded! "
End If
Catch ex As Exception
Label2.Text = " Failed to Upload, pls check your data or file format ! "
End Try
Next
End If
End If
End Sub
When i upload the xls file, the label displayed
"Please select a File to upload!", anything i missed out in the popup control? Please guide me on this, thanks in advance.
EDIT*
I have changed the upload control to this and it no longer showed the "Please select a File to upload!" now there is another error showed "File is not in correct format - Details: F11", the error seems to lie on the column [1]-[12], but the excel column is 1-12 and the column in database is [1]-[12].how can i achieve this? ( Solved by changing the number to F11 and so on.)
<dx:ASPxUploadControl runat="server" ClientInstanceName="XXUpload" ID="XXUpload" Width="600px" >
<ValidationSettings AllowedFileExtensions=".xls"></ValidationSettings>
</dx:ASPxUploadControl>
Edit 2*
The data has uploaded successfully to sql server and now another problem occurred, the data uploaded to sql server wont show in the UpdateSplitGrid gridview although i have declared this in my code.
If res > 0 Then
Label2.Text = res.ToString + " Records Successfully Uploaded! "
UpdateSplitGrid.DataBind()
Your ASPxUploadControl, the XXUpload, doesn't have any function to execute when upload is complete. I suggest you use OnFileUploadComplete event with FileUploadMode="OnPageLoad".

Make If Statments Using Gridview LinkButtons

I have 2 Linkbuttons inside each row of my gridview.
I want to know how I can use If statements to determine which changes should be made.
My current If statements(which I know are wrong) are as follows:
If LinkButton1.Text = "Update" Then
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
What do I use in place of my lines If LinkButton1.Text = "Update"
Update:
I added CommandName="UpdateRow" and "DeleteRow" to HTML Linkbutton and did the following:
If LinkButton1.CommandName = "UpdateRow"
and
ElseIf LinkButton2.CommandName = "DeleteRow" Then
However, the Delete one simply Deletes the LinkButton and not the Database record which is weird?! Not sure why.
I also see that the Display button will only work once I click Delete, change page, go back to first page which has Delete Removed. So if Delete is present Display doesn't work.
UPDATED FULL VERSION THAT DOESN'T WORK
VERSION 1
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
' Dim counter As Integer = 0
' Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
If LinkButton1.commandName = "UpdateRow" Then
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.commandName = "DeleteRow" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE Classid = '" & strFilter & "'"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End If
End Sub
VERSION 2
Sub LinkButton1_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
Dim counter As Integer = 0
Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Update_Values", strSelect)
Response.Redirect("DispAdUpdate.aspx")
End Sub
Sub LinkButton2_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""*******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strFilter As String = " "
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End Sub
You should put strFilter = row.Cells(1).Text line above if statement (If LinkButton1.Text = "Update" Then).
It looks like doing this process is very hard.
I decided to do a "select" option instead since my question seemed difficult.
I do this like so:
For the select option row:
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
End Sub
Then making a delete and update button that takes that index as so....
Protected Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Dim conn As OleDbConnection = New OleDbConnection("Provider=""******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
If Page.IsValid Then
If DisplayClassifieds.SelectedIndex = -1 Then
Response.Write("<script language=""javascript"">alert('You must select a record.');</script>")
Exit Sub
End If
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
'DataKey is the DataKey that we labeled as Classid(same name as ID field in Oracle)
ClassifiedStr.Parameters.Add("val_id", OleDbType.Numeric).Value = CInt(DisplayClassifieds.SelectedDataKey.Value)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
....etc
The bottom "DataKey" code from my VB.net comes from the table options I made with the use of "DataKeyNames" value :
<asp:GridView ID="DisplayClassifieds" runat="server" align="center"
Width="100%" AllowSorting="True" AutoGenerateColumns="False"
AutoGenerateSelectButton="True" EnableModelValidation="True"
BorderColor="Black" BorderStyle="Solid" DataKeyNames="Classid" >
<Columns>
<asp:BoundField DataField="Classid" HeaderText="ID"
SortExpression="Date" Visible = "false">
<ItemStyle cssClass="grid_padding" />
</asp:BoundField>
....etc
</Columns>
</asp:GridView>
I'm not as familiar with using/calling stored procedures but, if it's not too much of a hassle, try typing your delete query out in the commandtext property, ex.
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE val_id = #val_id"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.AddWithValue("#val_id", strFilter)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
Since I haven't ever called stored procedures I am just guessing that it has something to do with the way you are calling it for delete

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

OnSelectedIndexChanged not working first selection, but will on subsequent selections

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.

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