Here is the code:
<%# Page Language="VB" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Dim SQLConn As SqlConnection = New SqlConnection()
Dim strSQL As String
Dim strFilter As String
Dim objCmd
Dim objReader As SqlDataReader
Dim DBComm As SqlCommand
Dim DBAdapt As SqlDataAdapter
Sub DBConnect
SQLConn.ConnectionString = ConfigurationSettings.AppSettings("CString")
SQLConn.Open()
End Sub
Sub DBDisconnect
SQLConn.close()
End Sub
Sub Page_Load
Dim ThisFilter As Object = ViewState("vsFilter")
If Not (ThisFilter Is Nothing) Then
strFilter = CStr(ThisFilter)
Else
strFilter = "All"
End If
If Not Page.IsPostBack Then
BindData(True)
End If
End Sub
Sub BindData(ByVal GetFresh As Boolean)
Call DBConnect()
Dim DTable As DataTable = Nothing
If ViewState("vsSortData") Is Nothing Or GetFresh Then
If Session("Agency_Name") = "Main Company" Then
strSQL = "SELECT LOGIN.Login_ID, LOGIN.Login_Last_Name + ', ' + LOGIN.Login_First_Name + ' ' + CASE WHEN Login_Middle_Name IS NULL THEN '' ELSE CONVERT(varchar, Login_Middle_Name) END AS FullName, AGENCY.Agency_Name, '(' + Substring(Login_Phone, 0, 4) + ') ' + Substring(Login_Phone, 4, 3) + '-' + Substring(Login_Phone, 7, 4) as Phone, LOGIN.Login_Email, CASE WHEN Login_Type = 'U' THEN 'User' WHEN Login_Type = 'I' THEN 'ISC' ELSE CONVERT(varchar, Login_Type) END AS LoginType, CASE WHEN Login_Account_Active = 'T' THEN 'Yes' WHEN Login_Account_Active = 'F' THEN 'No' ELSE CONVERT(varchar, Login_Account_Active) END AS AcctActive FROM LOGIN INNER JOIN AGENCY ON LOGIN.Login_Agency_ID = AGENCY.Agency_ID WHERE LOGIN.Login_Deleted = 'F'"
Else
strSQL = "SELECT LOGIN.Login_ID, LOGIN.Login_Last_Name + ', ' + LOGIN.Login_First_Name + ' ' + CASE WHEN Login_Middle_Name IS NULL THEN '' ELSE CONVERT(varchar, Login_Middle_Name) END AS FullName, AGENCY.Agency_Name, '(' + Substring(Login_Phone, 0, 4) + ') ' + Substring(Login_Phone, 4, 3) + '-' + Substring(Login_Phone, 7, 4) as Phone, LOGIN.Login_Email, CASE WHEN Login_Type = 'U' THEN 'User' WHEN Login_Type = 'I' THEN 'ISC' ELSE CONVERT(varchar, Login_Type) END AS LoginType, CASE WHEN Login_Account_Active = 'T' THEN 'Yes' WHEN Login_Account_Active = 'F' THEN 'No' ELSE CONVERT(varchar, Login_Account_Active) END AS AcctActive FROM LOGIN INNER JOIN AGENCY ON LOGIN.Login_Agency_ID = AGENCY.Agency_ID WHERE LOGIN.Login_Deleted = 'F' AND AGENCY.Agency_Name='" & Session("Agency_Name") & "'"
End If
DBComm = New SqlCommand(strSQL, SQLConn)
DBAdapt = New SqlDataAdapter(DBComm)
Dim DSet As New DataSet()
Try
DBAdapt.Fill(DSet)
DTable = DSet.Tables(0)
Catch EXC As SqlException
Me.lblMsg2.Text = EXC.Message
Return
Finally
SQLConn.Close()
End Try
ViewState("vsSortData") = DTable
Else
DTable = CType(ViewState("vsSortData"), DataTable)
End If
If strFilter = "All" Then
DTable.DefaultView.RowFilter = String.Empty
Else
DTable.DefaultView.RowFilter = "FullName LIKE '" & strFilter & "%'"
End If
Me.datagrid.DataSource = DTable.DefaultView
Me.datagrid.DataBind()
BuildAlphaPager()
Call DBDisconnect()
End Sub
Sub BuildAlphaPager()
Dim DTable As DataTable
If ViewState(("strLetter")) Is Nothing Then
Dim arrLetters As String() = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "All"}
DTable = New DataTable()
DTable.Columns.Add(New DataColumn("Letter", GetType(String)))
Dim i As Integer
For i = 0 To arrLetters.Length - 1
Dim DRow As DataRow = DTable.NewRow()
DRow(0) = arrLetters(i)
DTable.Rows.Add(DRow)
Next i
ViewState("strLetter") = DTable
Else
DTable = CType(ViewState("strLetter"), DataTable)
End If
Me.rptLetters.DataSource = DTable.DefaultView
Me.rptLetters.DataBind()
End Sub
Protected Sub rptLetters_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
If (e.Item.ItemType = ListItemType.Header) Then
ElseIf (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim lnkAlpha As LinkButton = CType(e.Item.FindControl("lnkAlpha"), LinkButton)
lnkAlpha.Text = DataBinder.Eval(e.Item.DataItem, "Letter")
lnkAlpha.CommandName = "Filter"
lnkAlpha.CommandArgument = DataBinder.Eval(e.Item.DataItem, "Letter")
Dim DRView As DataRowView = CType(e.Item.DataItem, DataRowView)
If CStr(DRView(0)) = strFilter Then
lnkAlpha.Enabled = False
End If
ElseIf (e.Item.ItemType = ListItemType.Footer) Then
End If
End Sub
Protected Sub rptLetters_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
If e.CommandName = "Filter" Then
strFilter = CStr(e.CommandArgument)
ViewState("vsFilter") = strFilter
BindData(False)
End If
End Sub
</script>
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server">
<font size="1" color="#FF0000"><strong><asp:label id="lblMsg2" runat="server" /></strong></font>
<div align="center"><h3>
<asp:Repeater ID="rptLetters" runat="server" OnItemDataBound="rptLetters_ItemDataBound" OnItemCommand="rptLetters_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkAlpha" runat="server" />
</ItemTemplate>
</asp:Repeater>
</h3></div>
<asp:DataGrid ID="datagrid" runat="server" AutoGenerateColumns="False" AllowSorting="true" width="725px" BackColor="Gray" BorderWidth="0" BorderStyle="None" BorderColor="#DEBA84" Font-Size="XX-Small" CellPadding="3" CellSpacing="1">
<HeaderStyle font-size="XX-Small" font-names="Verdana" font-bold="True" horizontalalign="Center" forecolor="White" bordercolor="White" backcolor="#1E3769" />
<AlternatingItemStyle BackColor = "Gray" CssClass = "row" />
<ItemStyle CssClass = "row" />
<Columns>
<asp:TemplateColumn ItemStyle-Width="200px" ItemStyle-HorizontalAlign="center" HeaderText="Full Name" SortExpression="Login_Last_Name">
<ItemTemplate> <a style="color: #000000;" href="mailto:<%# Container.DataItem("Login_Email")%>">
<%# Container.DataItem("FullName")%> </a> </ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn ItemStyle-Width="160px" ItemStyle-HorizontalAlign="center" DataField="Agency_Name" HeaderText="Agency Name" SortExpression="Agency_Name"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="110px" ItemStyle-HorizontalAlign="center" DataField="Phone" HeaderText="Phone Number" SortExpression="Login_Phone"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="80px" ItemStyle-HorizontalAlign="center" DataField="LoginType" HeaderText="User Type" SortExpression="Login_Type"></asp:BoundColumn>
<asp:BoundColumn ItemStyle-Width="115px" ItemStyle-HorizontalAlign="center" DataField="AcctActive" HeaderText="Account Active" SortExpression="Login_Account_Active"></asp:BoundColumn>
<asp:TemplateColumn ItemStyle-Width="40px" ItemStyle-HorizontalAlign="center" HeaderText="Details">
<ItemTemplate>
<a style="color: #000000;" href="javascript:openDetail('userDetail.aspx?id=<%# Container.DataItem("Login_ID")%>');">
Details </a> </ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn ItemStyle-Width="25px" ItemStyle-HorizontalAlign="center" HeaderText="Edit">
<ItemTemplate> <a style="color: #000000;" href="edAccounts.aspx?f=e&id=<%# Container.DataItem("Login_ID")%>">
Edit </a> </ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
I just want the Full Name column (first column, FullName) to be in alphabetical order by default, and then if they click on a specific column then that column should arrange itself alphabetically. This used to work until I applied the above solution to paginate based on the letter in the name.
I have tried modifying the SQL queries and including "ORDER BY FullName" and "ORDER BY LOGIN.Login_Last_Name" and many other things but can't seem to get it to order by this by default, nor does any other column sort when clicked on as should occur. Somehow the alphabetic pagination is not allowing these fields to be sorted any further.
This is ASP.NET 2.0 with VB. Help?
I recommend this example and i as a personal note I would recommend using the example with the ObjectDataSource as it allows you to separate your presentation layer (pages) prom your data access layer (classes that execute sql and retrieve the data)
Related
I'm trying to export data however it only extract the data in current paging. And I need to go to another paging to download another. Is there any where to download all data in the source?
Below is my aspx code:
<asp:datagrid id="dgAmount" Visible=false runat="server" CssClass="item01Nxx08" Width="100%" CellPadding="3"
BorderColor="#DEDFDE" BorderStyle="None" PageSize="50" AutoGenerateColumns="False" AllowSorting="True"
AllowPaging="True" BackColor="White" BorderWidth="1px" GridLines="Vertical" ForeColor="Black">
<asp:BoundColumn DataField="No" SortExpression="No" HeaderText="No" visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="Action" SortExpression="Action" HeaderText="Action"></asp:BoundColumn>
<asp:BoundColumn DataField="AppName" SortExpression="AppName" HeaderText="Approver Name"></asp:BoundColumn>
<asp:BoundColumn DataField="MIAmount" SortExpression="MIAmount" HeaderText="MI Amount"></asp:BoundColumn>
<asp:BoundColumn DataField="By" SortExpression="By" HeaderText="By">
</asp:BoundColumn>
<asp:BoundColumn DataField="Date" SortExpression="Date" HeaderText="Date">
</asp:BoundColumn>
</asp:DataGrid>
And below is my vb code:
System.Web.HttpContext.Current.Response.Clear()
System.Web.HttpContext.Current.Response.Buffer = True
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=" & fileName & ".xls;")
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
System.Web.HttpContext.Current.Response.Charset = ""
'set the response mime type for excel
'create a string writer
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
'create an htmltextwriter which uses the stringwriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
htmlWrite.WriteLine("<b><u>" & header & "</u></b><br /><br />")
'instantiate a datagrid
Dim dg As New DataGrid()
Dim dt As New DataTable, dr As DataRow
dt.Columns.Add(New DataColumn("No", GetType(Integer)))
dt.Columns.Add(New DataColumn("Action", GetType(String)))
dt.Columns.Add(New DataColumn("Approver Name", GetType(String)))
dt.Columns.Add(New DataColumn("MI Amount", GetType(String)))
dt.Columns.Add(New DataColumn("By", GetType(String)))
dt.Columns.Add(New DataColumn("Date", GetType(String)))
Dim tempDg As DataGrid = dgAmount
For Each item As DataGridItem In tempDg.Items
dr = dt.NewRow()
dr("No") = item.Cells(0).Text
dr("Action") = item.Cells(1).Text
dr("Approver Name") = item.Cells(2).Text
dr("MI Amount") = item.Cells(3).Text
dr("By") = item.Cells(4).Text
dr("Date") = item.Cells(5).Text
dt.Rows.Add(dr)
Next
dg.DataSource = dt
dg.DataBind()
dg.EnableViewState = False
dg.GridLines = GridLines.None
dg.HeaderStyle.Font.Name = "Verdana"
dg.HeaderStyle.Font.Size = 8
dg.HeaderStyle.Font.Bold = True
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
dg.HeaderStyle.ForeColor = Drawing.Color.White
dg.HeaderStyle.BackColor = Drawing.Color.Black
dg.ItemStyle.Font.Name = "Verdana"
dg.ItemStyle.Font.Size = 8
dg.ItemStyle.VerticalAlign = VerticalAlign.Top
'bind the modified datagrid
'tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite)
'output the html
System.Web.HttpContext.Current.Response.Write(stringWrite.ToString)
System.Web.HttpContext.Current.Response.End()
System.Web.HttpContext.Current.Response.Redirect("")
Turn Paging off before bind/export. grid.AllowPaging = false;
i have successfully been able to calculate a monthly depreciable amount of an asset using straight line formula
I'm having issues using the doubline balance line formular as I'm not getting my expected result
formula = (2* depreciation ) / lifeMonth
below is my backend code
Dim acquiredDate As DateTime = Convert.ToDateTime(2019, 11, 15)
Dim startMonth As DateTime = Convert.ToDateTime(2019, 11, 15)
Dim depreciation As Double = "10000"
Dim slavege As Double = "10"
Dim lifeMonth As Integer = "12"
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Month")
dt.Columns.Add("Depreciation", GetType(Decimal))
dt.Columns.Add("Accumulated", GetType(Decimal))
dt.Columns.Add("BookValue", GetType(Decimal))
Dim i As Integer = 0
Dim depreciationExpense As Double = (2 * depreciation) / lifeMonth
Dim bookValue As Double = depreciation - depreciationExpense
Dim newDepreciationExpense As Double = 0
While startMonth < acquiredDate.AddMonths(lifeMonth)
Dim dr As DataRow = dt.NewRow()
dr("Month") = startMonth.ToString("MMM yyyy")
dr("Depreciation") = depreciationExpense
If i = 0 Then
dr("Accumulated") = Math.Round(depreciationExpense, 2)
dr("BookValue") = Math.Round(bookValue, 2)
newDepreciationExpense = depreciationExpense
Else
newDepreciationExpense = newDepreciationExpense + depreciationExpense
bookValue = bookValue - depreciationExpense
dr("Accumulated") = Math.Round(newDepreciationExpense, 2)
dr("BookValue") = Math.Round(bookValue, 2)
End If
dt.Rows.Add(dr)
startMonth = startMonth.AddMonths(1)
i += 1
End While
Me.gvData.DataSource = dt
Me.gvData.DataBind()
below is my front end(html)
<asp:GridView runat="server" ID="gvData" AutoGenerateColumns="false" CssClass="table table-bordered table-striped table-depreciation">
<Columns>
<asp:BoundField DataField="Month" HeaderText="Month" />
<asp:BoundField DataField="Depreciation" HeaderText="Depriciation Expenses" DataFormatString="{0:N2}" />
<asp:BoundField DataField="Accumulated" HeaderText="Accumulate Deprication at Month-End" DataFormatString="{0:N2}" />
<asp:BoundField DataField="BookValue" HeaderText="Book Value at Month-End" DataFormatString="{0:N2}" />
</Columns>
</asp:GridView>
the result I'm getting
my expected result
I have a drop down list that I am populating from the code behind and I have a Gridview control below the drop down list that I am also populating from code behind. My goal is to select a department from the drop down list and populate the Gridview control will all employees in that department
This is my code to populate my Gridview control:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
LoadDataGrid()
FillWithDepartments()
End If
End Sub
Private Sub LoadDataGrid()
Try
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)
Using cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] , CostCentre AS [Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No] , EmployeeCodes.Code AS [Clock No] ,MedicalResults.[DateTested] AS [Date Tested] , MedicalResults.[NextDueDate] AS [Next Due Date] , MedicalResults.ECGDate AS [ECG] , MedicalResults.LungFunctionDate AS [Lungfunction] , MedicalResults.AudioGramDate AS [Hearing Test] , MedicalResults.EyeTestDate AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND MedicalResults.EmployeeID = EmployeeCodes.EmployeeID Order By DateTested DESC", conn)
Dim sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
Catch ex As Exception
End Try
End Sub
This is the code to populate my drop down list from code behind:
Protected Sub FillWithDepartments()
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("###").ConnectionString)
'conn.Open()
Dim cmd As New SqlCommand("SELECT Code , ShortDescription FROM Departments", conn)
Dim adapter As New SqlDataAdapter(cmd)
Dim tbl As New DataTable()
adapter.Fill(tbl)
drplstDepartment.DataSource = tbl
drplstDepartment.DataTextField = "ShortDescription"
drplstDepartment.DataValueField = "Code"
drplstDepartment.DataBind()
' conn.Close()
End Using
End Sub
Front End Code for Drop Down List
<asp:DropDownList ID="drplstDepartment" OnSelectedIndexChanged="drplstDepartment_SelectedIndexChanged" CssClass="form-control mb-2 mr-sm-2" runat="server" AutoPostBack="true">
</asp:DropDownList>
Front End Code Fro Grid View
<asp:GridView RowStyle-CssClass="text-center" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" AllowPaging="true" class="table table-default table-striped table-bordered table-condensed table-responsive table-hover" border="1" ID="GridView1" runat="server" HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Middle" HeaderStyle-BackColor="#6C6C6C" HeaderStyle-ForeColor="White" RowStyle-BackColor="#eeeeee" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" RowStyle-ForeColor="#000" AutoGenerateColumns="false" >
<Columns>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Department" HeaderText = "Department"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Cost Centre" HeaderText = "Cost Centre"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Name" HeaderText = "Name" />
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Surname" HeaderText = "Surname"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "ID No" HeaderText = "ID No"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Clock No" HeaderText = "Clock No"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "Date Tested" HeaderText = "Date Tested"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "Next Due Date" HeaderText = "Next Due Date"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "ECG" HeaderText = "ECG"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "Lungfunction" HeaderText = "Lungfunction"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "Hearing Test" HeaderText = "Hearing Test"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextFormatString="{0:dd/MM/yyyy}" DataTextField= "Eye Test" HeaderText = "Eye Test"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Other Problems" HeaderText = "Other Problems"/>
<asp:ButtonField ItemStyle-Width = "150px" DataTextField= "Notes" HeaderText = "Notes"/>
</Columns>
</asp:GridView>
This is the code that is not firing
Protected Sub drplstDepartment_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim dt As DataTable = New DataTable()
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("#").ToString())
Dim cmd As New SqlCommand("SELECT Departments.ShortDescription AS [Department] , CostCentre AS [ Cost Centre] , FirstName AS [Name] , LastName AS [Surname] , MedicalResults.EmployeeID AS [ID No] , EmployeeCodes.Code AS [Clock No] ,CONVERT(nvarchar(10), MedicalResults.[DateTested], 101) AS [Date Tested] ,CONVERT(nvarchar(10), MedicalResults.[NextDueDate], 101) AS [Next Due Date] , CONVERT(nvarchar(10), MedicalResults.ECGDate, 101) AS [ECG] , CONVERT(nvarchar(10), MedicalResults.LungFunctionDate, 101) AS [Lungfunction] , CONVERT(nvarchar(10), MedicalResults.AudioGramDate, 101) AS [Hearing Test] , CONVERT(nvarchar(10), MedicalResults.EyeTestDate, 101) AS [Eye Test] , OtherProblems AS [Other Problems] , Notes FROM MedicalResults, EmployeeCodes , EmployeevsPositionLink , PositionCodes , Departments WHERE MedicalResults.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND MedicalResults.EmployeeID = EmployeeCodes.EmployeeID AND (Departments.ShortDescription = #ShortDescription)", conn)
cmd.Parameters.AddWithValue("#ShortDescription", drplstDepartment.SelectedValue)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Sub
Try this instead in your drplstDepartment_SelectedIndexChanged event:
Dim cmd As New SqlCommand("SELECT
...
FROM
...
WHERE
...
AND (Departments.Code = #Code)", conn)
cmd.Parameters.AddWithValue("#Code", drplstDepartment.SelectedItem.Value)
#Code matches drplstDepartment.SelectedItem.Value, #ShortDescription matches drplstDepartment.SelectedItem.Text.
I would think this code should be very simple and straight forward but I'm having issues. The sub below is called on the page load. It is nestled between similar functions that load other drop down lists. All the rest of the drop downs are populating but these are not. The other drop downs subs use the same With clause but are binding to a DataSet (of one table) that is populated with a stored procedure call to the database rather than binding to a static DataTable.
VB Code:
Private Sub LoadEquations()
Dim dtMain As DataTable
Dim dtGypsum As DataTable
Dim dr As DataRow
dtMain.Columns.Add("Text")
dtMain.Columns.Add("Value")
dr = dtMain.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
dr = dtMain.NewRow
dr.Item("Text") = "Build"
dr.Item("Value") = "B"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
dr = dtMain.NewRow
dr.Item("Text") = "Maintain"
dr.Item("Value") = "M"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
With Me.ddMainEquation
.DataSource = dtMain
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
dtGypsum.Columns.Add("Text")
dtGypsum.Columns.Add("Value")
dr = dtGypsum.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
dr = dtGypsum.NewRow
dr.Item("Text") = "pH Base"
dr.Item("Value") = "P"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
dr = dtGypsum.NewRow
dr.Item("Text") = "% Sodium Base"
dr.Item("Value") = "S"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
With Me.ddGypsumEquation
.DataSource = dtGypsum
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
End Sub
DNN / ASP Code:
<tr>
<td>
<asp:Label ID="lblMainEquation" runat="server"
CssClass="FormLabelLeft">Main Equation</asp:Label></td>
<td>
<asp:Label ID="lblGypsumEquation" runat="server"
CssClass="FormLabelLeft">Gypsum Equation</asp:Label></td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddMainEquation" TabIndex="34"
runat="server" CssClass="FormField"></asp:DropDownList></td>
<td>
<asp:DropDownList ID="ddGypsumEquation" TabIndex="34"
runat="server" CssClass="FormField"></asp:DropDownList></td>
</tr>
What am I missing? I am using an older DNN platform 2.0.
You should declare your datatable as a New object
Try below:
Private Sub LoadEquations()
Dim dtMain As New DataTable
Dim dtGypsum As New DataTable
Dim dr As DataRow
dtMain.Columns.Add("Text")
dtMain.Columns.Add("Value")
dr = dtMain.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtMain.Rows.Add(dr)
dr = dtMain.NewRow
dr.Item("Text") = "Build"
dr.Item("Value") = "B"
dtMain.Rows.Add(dr)
dr = dtMain.NewRow
dr.Item("Text") = "Maintain"
dr.Item("Value") = "M"
dtMain.Rows.Add(dr)
With ddMainEquation
.DataSource = dtMain
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
dtGypsum.Columns.Add("Text")
dtGypsum.Columns.Add("Value")
dr = dtGypsum.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtGypsum.Rows.Add(dr)
dr = dtGypsum.NewRow
dr.Item("Text") = "pH Base"
dr.Item("Value") = "P"
dtGypsum.Rows.Add(dr)
dr = dtGypsum.NewRow
dr.Item("Text") = "% Sodium Base"
dr.Item("Value") = "S"
dtGypsum.Rows.Add(dr)
With ddGypsumEquation
.DataSource = dtGypsum
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
End Sub
By the way, AcceptChanges() is not really required for each time after you add in a new row. Calling AcceptChanges after adding new row will actually turn the DataRowState of your newly added DataRow from Added to Unchanged. check this out.
I am having problems trying to get a rowcommand event to fire in a gridview. I followed the code example from MSDNet but I cannot figure out why it is not working. The code is below. Thank you.
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<PagerSettings PageButtonCount="20" />
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" >
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Interest">
<ItemTemplate>
<asp:DropDownList ID="ddlProductInterest" runat="server" SelectedValue='<%# Bind("ProductInterest") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="TestButton" Text="Button" CommandName="Test"
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="center" />
<ItemStyle HorizontalAlign="center" />
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
++Code Behind +++
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Test" Then
Dim index = Convert.ToInt32(e.CommandArgument)
Dim row = GridViewProducts.Rows(index)
Dim MyString As String = row.Cells(0).Text
strSQL = "INSERT INTO tblClosedProducts (" & _
"Product, ClosedBy, DateClosed " & _
") VALUES (" & _
"#Product, #ClosedBy, #DateClosed " & _
")"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#Product", SqlDbType.VarChar), _
New SqlParameter("#ClosedBy", SqlDbType.VarChar), _
New SqlParameter("#DateClosed", SqlDbType.SmallDateTime) _
}
MyParameters1(0).Value = row.Cells(0).Text
MyParameters1(1).Value = GetInfo.GetFullName(UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4)))
MyParameters1(2).Value = DateAdd("h", -1, Now())
objData.SQLExecuteNonQuery(strSQL, CommandType.Text, MyParameters1)
End If
End Sub
Your gridview doesnt have the event wired up in its markup.
Try adding in onrowcommand="GridViewProducts_RowCommand" so it looks like this:
<asp:GridView ID="GridViewProducts" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="5" CellSpacing="1" DataKeyNames="Pkey"
DataSourceID="SqlDataSourceProducts" ForeColor="Black" GridLines="Vertical"
onrowcommand="GridViewProducts_RowCommand">
#rtpHarry is correct, and that is a valid way to wire up the event. Another method of wiring the event would be to change the signature of your method in the code behind to add Handles Me.GridViewProducts.RowCommand to the end:
Sub GridViewProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles Me.GridViewProducts.RowCommand
protected void Add_Update_Remove_Row(int Index, string Operation)
{
//DataTable dt = (DataTable)ViewState["Table_BinaryPayment"];
int ID = Index;
Label lblddt = (Label)GridView1.Rows[Index].FindControl("Label2");
Label lblttm = (Label)GridView1.Rows[Index].FindControl("Label1");
Label lblid = (Label)GridView1.Rows[Index].FindControl("lblID");
Label lblaeamt = (Label)GridView1.Rows[Index].FindControl("lblamt");
Label lblprojID = (Label)GridView1.Rows[Index].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[Index].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[Index].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[Index].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[Index].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[Index].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[Index].FindControl("lbladdtodeliver");
Label lblEID = (Label)GridView1.Rows[Index].FindControl("lblEID");
ViewState["DispTime"] = lblttm.Text;
ViewState["ExpTime"] = lblexpttime.Text;
if (Operation == "Modify")
{
//lblchqNo.Text = txtchequeNO1.Text;
//lblchqDate.Text = txtchequeDate1.Text;
//lblAccountNo.Text = txtAccountNo.Text;
//lblBName.Text = txtBankName.Text;
lblddt.Text = txtdispdate.Text;
if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
{
lblttm.Text = ViewState["DispTime"].ToString();
}
else
{
lblttm.Text = (ddldisphr.SelectedItem.Text + ":" + ddldispmin.SelectedItem.Text + ":" + ddldispsec.SelectedItem.Text);
}
if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
{
lblexpttime.Text = ViewState["ExpTime"].ToString();
}
else
{
lblexpttime.Text = (ddlexphr.SelectedItem.Text + ":" + ddlexpmin.Text + ":" + ddlexpsec.Text);
}
lblaeamt.Text = txtadvPayment.Text;
lblpaydetails.Text = txtpaymentdetails.Text;
lblexpdate.Text = txtexpdate.Text;
lblalloycodes.Text = ddlalloycode.SelectedItem.Text;
lblalloyrates.Text = txtalloyrate.Text;
lbladddelivered.Text = txtaadtodel.Text;
//ExecuteProcedures ex = new ExecuteProcedures(4);
//string proc="Inse_Clientorder";
//ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, lblddt.Text);
//ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//ex.Parameters.Add("#Enquiry_ID", SqlDbType.VarChar, ID );
//ex.Parameters.Add("#numAdvance_Amount", SqlDbType.Float , Convert.ToDouble(txtadvPayment.Text ));
//bool s = ex.InvokeProcedure(proc);
ExecuteProcedures ex = new ExecuteProcedures(12);
//string proc = "Inse_Clientorder123";
string proc = "Inse_Clientorder321";
ex.Parameters.Add("#dtPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblddt.Text));
//if (ddldisphr.SelectedItem.Text == "00" & ddldispmin.SelectedItem.Text == "00" & ddldispsec.SelectedItem.Text == "00")
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, ViewState["DispTime"]);
//}
//else
//{
// ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
//}
//if (ddlexphr.SelectedItem.Text == "00" & ddlexpmin.Text == "00" & ddlexpsec.Text == "00")
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, ViewState["ExpTime"]);
//}
//else
//{
// ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
//}
ex.Parameters.Add("#Dispath_Time", SqlDbType.VarChar, lblttm.Text);
ex.Parameters.Add("#ExpTime", SqlDbType.VarChar, lblexpttime.Text);
ex.Parameters.Add("#Advance_Payment_ID", SqlDbType.Int, Convert.ToInt32(lblid.Text));
ex.Parameters.Add("#numAdvance_Amount", SqlDbType.VarChar, lblaeamt.Text);
ex.Parameters.Add("#AlooyCode", SqlDbType.VarChar, lblalloycodes.Text);
ex.Parameters.Add("#numRate", SqlDbType.Float, Convert.ToDouble(lblalloyrates.Text));
ex.Parameters.Add("#vcrDescription", SqlDbType.VarChar, lbladddelivered.Text);
ex.Parameters.Add("#Client_Ordered_Projects_ID", SqlDbType.Int, Convert.ToInt32(lblprojID.Text));
ex.Parameters.Add("#Enquiry_ID", SqlDbType.Int, Convert.ToInt32(lblEID.Text));
ex.Parameters.Add("#dtExpectedPayment_Date", SqlDbType.DateTime, Convert.ToDateTime(lblexpdate.Text));
ex.Parameters.Add("#vcrPayment_Details", SqlDbType.VarChar, lblpaydetails.Text);
bool s = ex.InvokeProcedure(proc);
if (s == true)
{
CommonFunctions.Alert("Records Updated Successfully", this.Page);
}
else
{
CommonFunctions.Alert("Error In Updation", this.Page);
}
clear();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//if (e.CommandName == "Modify")
//{
// string strID = e.CommandArgument.ToString();
// strID = CommonFunctions.Encrypt(strID);
// Response.Redirect("Client_Order.aspx?Project_ID=" + strID);
//}
if (e.CommandName == "Modify")
{
string strID = e.CommandArgument.ToString();
int intRowIndex = ((GridViewRow)((LinkButton)e.CommandSource).Parent.Parent).RowIndex;
//Session[rowindex] = intRowIndex;
txtdispdate.Text = GridView1.Rows[intRowIndex].Cells[6].Text;
string strdisp = ((ddldisphr.SelectedItem.Text) + ":" + (ddldispmin.SelectedItem.Text) + ":" + (ddldispsec.SelectedItem.Text)).ToString();
lbltime.Text = GridView1.Rows[intRowIndex].Cells[7].Text;
Label lblClienorderiid = (Label)GridView1.Rows[intRowIndex].FindControl("lblcLOID");
Label lbledate = (Label)GridView1.Rows[intRowIndex].FindControl("Label2");
Label lbletime = (Label)GridView1.Rows[intRowIndex].FindControl("Label1");
Label lbliid = (Label)GridView1.Rows[intRowIndex].FindControl("lblID");
Label lblaamt = (Label)GridView1.Rows[intRowIndex].FindControl("lblamt");
Label lblEID = (Label)GridView1.Rows[intRowIndex].FindControl("lblEID");
Label lblprojID = (Label)GridView1.Rows[intRowIndex].FindControl("lblprojectID");
Label lblpaydetails = (Label)GridView1.Rows[intRowIndex].FindControl("lblpaydetails");
Label lblexpdate = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpDate");
Label lblexpttime = (Label)GridView1.Rows[intRowIndex].FindControl("lblExpTime");
Label lblalloycodes = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloycode");
Label lblalloyrates = (Label)GridView1.Rows[intRowIndex].FindControl("lblalloyRate");
Label lbladddelivered = (Label)GridView1.Rows[intRowIndex].FindControl("lbladdtodeliver");
ViewState["Index"] = intRowIndex;
ViewState["CommandName"] = e.CommandName;
txtdispdate.Text = lbledate.Text;
lbltime.Text = lbletime.Text;
txtadvPayment.Text = lblaamt.Text;
ddlalloycode.SelectedItem.Text = lblalloycodes.Text;
txtalloyrate.Text = lblalloyrates.Text;
txtaadtodel.Text = lbladddelivered.Text;
txtpaymentdetails.Text = lblpaydetails.Text;
txtexpdate.Text = lblexpdate.Text;
lblexptimess.Text = lblexpttime.Text;
pnl2.Visible = true;
//lbltime.Text = lbltm.Text;
//Add_Update_Remove_Row( intRowIndex , e.CommandName);
}
else if (e.CommandName == "Del")
{
string strID = e.CommandArgument.ToString();
string strSql = "Delete from Client_Order where Client_ID = " + strID;
string str_query = "Update Enquiry set OrderExecuted='No' where Enquiry_ID = " + strID;
//string str_query = "delete from Enquiry where Enquiry_ID = " + strID;
Dentry de = new Dentry();
de.RunCommand(strSql);
de.RunCommand(str_query);
Bind_Data();
}
else if(e.CommandName =="Invoice")
{
string strID = e.CommandArgument.ToString();
strID = CommonFunctions.Encrypt(strID);
string strType = CommonFunctions.Encrypt("New");
Response.Redirect("New_Order_Project_Invoice_Entry.aspx?Project_ID=" + strID + "&Type=" + strType);
}
else if (e.CommandName == "Delivered")
{
string strId = e.CommandArgument.ToString();
string str_query = "Update Enquiry set vcrDelivered='Yes' where Enquiry_ID=" + strId;
Dentry de = new Dentry();
de.RunCommand(str_query);
Bind_Data();
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");
lnk.Attributes.Add("onClick", "return confirm('Are you sure to delete this record?');");
}
}
Enable View State= true will solve your problem