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;
Related
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 want to add textBox in my dataTable.My dataTable is dynamically created and bind to gridView.When I try to add new row on button click gives me this error:
Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index
TextBox TextBox1 = (TextBox)GridView2.Rows[0].Cells[2].FindControl("TextBox1");
Here is my code:
Markup:
<asp:GridView ID="GridView2" runat="server"
ShowHeader="true"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CssClass="button2"
OnClick="btnTest_Click"
Text="-"
Width="100px"
Font-Bold="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TextBox1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
private void AddNewRecordRowToGridf()
{
//creating DataTable
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "Markici";
//creating columns for DataTable
dt.Columns.Add(new DataColumn("FirmaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Godina", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("KasaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("MarkicaID", typeof(System.Int64)));
dt.Columns.Add(new DataColumn("Datum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Masa", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VrabotenID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Artikal", typeof(System.String)));
dt.Columns.Add(new DataColumn("Cena1", typeof(System.String)));
dt.Columns.Add(new DataColumn("Kolicina", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("Smena", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("VkIznos", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("VkDanok", typeof(System.Decimal)));
dt.Columns.Add(new DataColumn("SysDatum", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("Vid", typeof(System.String)));
dt.Columns.Add(new DataColumn("EdMera", typeof(System.String)));
dt.Columns.Add(new DataColumn("ArtikalID", typeof(System.String)));
dt.Columns.Add(new DataColumn("TarifaID", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("Zabeleshka", typeof(System.String)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["Markici2"] = dt;
if (ViewState["Markici2"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici2"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].Cells[2].FindControl("TextBox1");
//Creating new row and assigning values
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label12.Text;
drCurrentRow["Cena1"] = Label13.Text;
if (Session["MinusVrganj"] != null)
{
drCurrentRow["Kolicina"] = Convert.ToInt32(Session["MinusVrganj"]) + Counter; //Label5.Text; //count;
}
drCurrentRow["Kolicina"] = Label11.Text; //count;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label17.Text;//Counter1 * Convert.ToDecimal(Label13.Text); //Label17.Text;
drCurrentRow["VkDanok"] = Label18.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label24.Text;
drCurrentRow["Edmera"] = Label16.Text;
drCurrentRow["ArtikalID"] = Label34.Text;
drCurrentRow["TarifaID"] = Label14.Text;
drCurrentRow["Zabeleshka"] = TextBox1.Text;
}
dtCurrentTable.Rows.Add(drCurrentRow);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
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)
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