I am having issues with the databind method of the gridview control I could use some help on. Some background... I have a search interface with a variety of textboxes (First Name, Last Name, Year, Gender etc.) The user will enter some data and press the search button. At which time I am dynamically generating the SQL for the datasource and binding it to the gridview control.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
' Check Program Year
If ddYear.SelectedValue = 0 Then
lblStatus.Text = "Please select a program year!"
Exit Sub
Else
lblStatus.Text = ""
End If
ds1.SelectCommand = "SELECT [StudentId], [ProgramYear], [LastName], [Middle], [FirstName], [HighSchoolCode], [Sex], [DateOfBirth] FROM [Student] WHERE [ProgramYear] = " & ddYear.SelectedValue & ""
Dim useCase As Integer = 0
If tbFname.Text <> "" Then useCase = 1
If tbLname.Text <> "" Then useCase = 2
If tbFname.Text <> "" And tbLname.Text <> "" Then useCase = 3
If tbFname.Text <> "" And tbM.Text <> "" Then useCase = 4
If tbID.Text <> "" Then useCase = 5
If tbHSCode.Text <> "" Then useCase = 6
If tbLname.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 7
If tbHSCode.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 8
Select Case useCase
Case 1 'First Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%')"
Case 2 'Last Name
ds1.SelectCommand += " and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 3 'First and Last Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 4 'First and Middle
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([Middle] = '" & tbM.Text & "')"
Case 5 'Student ID
ds1.SelectCommand += " and ([StudentId] = '" & tbID.Text & "')"
Case 6 'HS Code
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "')"
Case 7 'Last Name and Sex
ds1.SelectCommand += " and ([Sex] = '" & ddGender.SelectedValue & "' and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%'))"
Case 8 'HS Code and Sex
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "' and [Sex] = '" & ddGender.SelectedValue & "')"
Case Else
ds1.SelectCommand += " order by [LastName] desc"
End Select
ds1.DataBind()
GridView1.DataBind()
End Sub
This works well however when I enable paging and apply the OnPageIndexChanging method as below I run into trouble.
Protected Sub gridview1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
gridview1.PageIndex = e.NewPageIndex
GridView1.DataSource = ds1
gridview1.databind()
End Sub
What happens is that I click on the paging footer of the gridview to change pages and the gridview does not apply the new binding until I press the submit button again. I am not sure why this is happening any advice is appreciated.
Gridview:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="StudentId" DataSourceID="ds1" AllowPaging="True" PageSize="15">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>.
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Id" InsertVisible="False" SortExpression="StudentId">
<ItemTemplate>
<a href="searchDetail.aspx?StudentID=<%# eval("StudentId") %>" >
<asp:Label ID="xyz" runat="server" Text='<%# Bind("StudentId") %>' /></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="Middle" HeaderText="Middle" SortExpression="Middle" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Sex" HeaderText="Sex" SortExpression="Sex" />
<asp:BoundField DataField="HighSchoolCode" HeaderText="HS Code" SortExpression="HighSchoolCode" />
<asp:BoundField DataField="ProgramYear" HeaderText="Program Year" SortExpression="ProgramYear" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
DS1
<asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:NMERITEXString %>"></asp:SqlDataSource>
What you need to do in gridview1_PageIndexChanging is setting gridview1.PageIndex and do the same thing as in btnSubmit_Click.
To avoid code repetition, move the content of btnSubmit_Click to a separate sub, let's call it LoadGrid
Private Sub LoadGrid()
' Check Program Year
If ddYear.SelectedValue = 0 Then
lblStatus.Text = "Please select a program year!"
Exit Sub
Else
lblStatus.Text = ""
End If
ds1.SelectCommand = "SELECT [StudentId], [ProgramYear], [LastName], [Middle], [FirstName], [HighSchoolCode], [Sex], [DateOfBirth] FROM [Student] WHERE [ProgramYear] = " & ddYear.SelectedValue & ""
Dim useCase As Integer = 0
If tbFname.Text <> "" Then useCase = 1
If tbLname.Text <> "" Then useCase = 2
If tbFname.Text <> "" And tbLname.Text <> "" Then useCase = 3
If tbFname.Text <> "" And tbM.Text <> "" Then useCase = 4
If tbID.Text <> "" Then useCase = 5
If tbHSCode.Text <> "" Then useCase = 6
If tbLname.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 7
If tbHSCode.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 8
Select Case useCase
Case 1 'First Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%')"
Case 2 'Last Name
ds1.SelectCommand += " and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 3 'First and Last Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 4 'First and Middle
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([Middle] = '" & tbM.Text & "')"
Case 5 'Student ID
ds1.SelectCommand += " and ([StudentId] = '" & tbID.Text & "')"
Case 6 'HS Code
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "')"
Case 7 'Last Name and Sex
ds1.SelectCommand += " and ([Sex] = '" & ddGender.SelectedValue & "' and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%'))"
Case 8 'HS Code and Sex
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "' and [Sex] = '" & ddGender.SelectedValue & "')"
Case Else
ds1.SelectCommand += " order by [LastName] desc"
End Select
ds1.DataBind()
GridView1.DataSource = ds1;
GridView1.DataBind()
End Sub
then call LoadGrid() inside btnSubmit_Click
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'set to first page
gridview1.PageIndex = 0
LoadGrid()
End Sub
and also call LoadGrid() in gridview1_PageIndexChanging. Don't forget to add Handles gridview1.PageIndexChanging
Protected Sub gridview1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview1.PageIndexChanging
gridview1.PageIndex = e.NewPageIndex
LoadGrid()
End Sub
Ok I have it working now...
I had to add the loadgrid() sub to the page load as follows. Thanks for your assistance!
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
LoadGrid()
End If
End Sub
Related
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".
I am trying to learn how to put totals on my gridview and have been searching for 2 days to find why mine don't work. The onrowdatabound event fires, but it doesn't recognize the rows as datarows, it only picks up the footer (I added a textbox and put the value in to make sure I wasn't losing it). I am very new to this and am probably doing something wrong that is very simple.
my codebehind is
Protected Sub WeeklyGridView_RowDataBound(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs) Handles WeeklyGridView.OnRowDataBound
Dim appleTotal As Integer = 0
Dim orangeTotal As Integer = 0
Dim bananaTotal As Integer = 0
Dim pearTotal As Integer = 0
Dim grapeTotal As Integer = 0
Dim peachTotal As Integer = 0
Dim cherryTotal As Integer = 0
Dim pineTotal As Integer = 0
Dim totalTotal As Integer = 0
Dim ThedataType As String
ThedataType = e.Row.RowType.ToString
TextBox1.Text = ThedataType 'this always shows Footer
If e.Row.RowType = DataControlRowType.DataRow Then 'this never fires
appleTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Apple"))
orangeTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Orange"))
bananaTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Banana"))
pearTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Pear"))
grapeTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Grape"))
peachTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Peach"))
cherryTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Cherry"))
pineTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Pine"))
totalTotal += Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, _
"TOTAL"))
ElseIf e.Row.RowType = DataControlRowType.Footer Then 'this always fires
e.Row.Cells(0).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = appleTotal.ToString("g")
e.Row.Cells(4).Text = orangeTotal.ToString("g")
e.Row.Cells(5).Text = bananaTotal.ToString("g")
e.Row.Cells(6).Text = pearTotal.ToString("g")
e.Row.Cells(7).Text = grapeTotal.ToString("g")
e.Row.Cells(8).Text = peachTotal.ToString("g")
e.Row.Cells(9).Text = cherryTotal.ToString("g")
e.Row.Cells(10).Text = pineTotal.ToString("g")
e.Row.Cells(11).Text = totalTotal.ToString("g")
e.Row.Font.Bold = True
End If
End Sub
The gridview is updated based on criteria selected by the user and is made visible and populated when they click on a search button.
The ridiculous code for the search button is: (and I know it's terrible but I'm trying)
Protected Sub SearchButton_Click(sender As Object, e As ImageClickEventArgs) Handles SearchButton.Click
Dim wherecls As String = "trees in ("
Dim whereFNcls As String = "fruitNumber between ("
Dim whereString As String = ""
Dim i As Integer = 0
Dim selectQry As String = "SELECT cast(trees as varchar(3)) as Trees, MIN(fruitnumber) AS FN_Start, MAX(fruitnumber) AS FN_End, COUNT(CASE WHEN fruitType = 'apple' THEN 1 ELSE NULL END) AS apple, COUNT(CASE WHEN fruitType = 'orange' THEN 1 ELSE NULL END) AS orange, COUNT(CASE WHEN fruitType = 'banana' THEN 1 ELSE NULL END) AS banana, COUNT(CASE WHEN fruitType = 'pear' THEN 1 ELSE NULL END) AS pear, COUNT(CASE WHEN fruitType = 'grape' THEN 1 ELSE NULL END) AS grape, COUNT(CASE WHEN fruitType = 'peach' THEN 1 ELSE NULL END) AS peach, COUNT(CASE WHEN fruitType = 'cherry' THEN 1 ELSE NULL END) AS cherry, COUNT(CASE WHEN fruitType = 'pine' THEN 1 ELSE NULL END) AS pine, COUNT(CASE when dcosg is not null THEN 1 ELSE NULL END) AS Total FROM fruitReport WHERE (orchard = #orchard) and "
orchardTextBox.Text = orchardDropDown.SelectedValue
' check if items selected in both listboxes
If trees_Listbox.Items.Count > 0 Then
If fruitminListBox.Items.Count > 0 Then
'cycle through items in fruitnum listbox to create an "in" clause for sql query
For Each item As ListItem In trees_Listbox.Items
whereString += String.Join(",", item) + ", "
Next
whereString = Left(whereString, Len(whereString) - 2) + ")"
selectQry += "(" + wherecls + whereString + ")"
whereFNcls = "(fruitNumber between "
For Each itemFNmin As ListItem In fruitminListBox.Items
'create a "between" clause for the min and max FN values entered by user.
whereOEcls += itemFNmin.Value + " and " + fruitmaxListBox.Items(i).ToString + ") or (fruitNumber between " '(fruitnumber between number and number) or
i += 1
Next
'trim off the last text portion of the whereOEcls
whereOEcls = Left(whereOEcls, Len(whereFNcls) - 25)
selectQry += " and (" + whereFNcls + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
Else
'see if FN is empty but trees is selected
For Each item As ListItem In trees_Listbox.Items
whereString += String.Join(",", item) + ", "
Next
whereString = Left(whereString, Len(whereString) - 2)
selectQry += wherecls + whereString + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
End If
Else
If fruitminListBox.Items.Count > 0 Then
'check if trees is empty but FN is selected
whereFNcls = "(fruitNumber between "
For Each itemFNmin As ListItem In fruitminListBox.Items
'create a "between" clause for the min and max FN values entered by user.
whereFNcls += itemFNmin.Value + " and " + fruitmaxListBox.Items(i).ToString + ") or (fruitNumber between " '(fruitnumber between number and number) or
i += 1
Next
whereFNcls = Left(whereFNcls, Len(whereFNcls) - 26)
selectQry += whereFNcls + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
Else
'if both are empty search only on orchard
selectQry = Left(selectQry, Len(selectQry) - 5) + " group by trees order by trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
End If
End If
End Sub
And lastly, my gridview is...
<asp:GridView ID="WeeklyGridView" runat="server" HorizontalAlign="Center" DataSourceID="fruityData" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" Visible="False" ShowFooter="True" ShowHeaderWhenEmpty="True">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="trees" HeaderText="trees" SortExpression="trees" />
<asp:BoundField DataField="FN_Start" HeaderText="FN_Start" SortExpression="FN_Start" ReadOnly="True" />
<asp:BoundField DataField="FN_End" HeaderText="FN_End" SortExpression="FN_End" ReadOnly="True" />
<asp:BoundField DataField="apple" HeaderText="apple" SortExpression="apple" ReadOnly="True" />
<asp:BoundField DataField="orange" HeaderText="orange" SortExpression="orange" ReadOnly="True" />
<asp:BoundField DataField="banana" HeaderText="banana" SortExpression="banana" ReadOnly="True" />
<asp:BoundField DataField="pear" HeaderText="pear" SortExpression="pear" ReadOnly="True" />
<asp:BoundField DataField="grape" HeaderText="grape" SortExpression="grape" ReadOnly="True" />
<asp:BoundField DataField="peach" HeaderText="peach" SortExpression="peach" ReadOnly="True" />
<asp:BoundField DataField="cherry" HeaderText="cherry" SortExpression="cherry" ReadOnly="True" />
<asp:BoundField DataField="pine" HeaderText="pine" SortExpression="pine" ReadOnly="True" />
<asp:BoundField DataField="TOTAL" HeaderText="TOTAL" SortExpression="TOTAL" ReadOnly="True" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
<asp:SqlDataSource ID="fruityData" runat="server" ConnectionString="<%$ ConnectionStrings:fruityStuff %>" >
<SelectParameters>
<asp:ControlParameter ControlID="orchardTextBox" DefaultValue="theGrove" Name="orchard" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Any and all help would be greatly appreciated.
You don't call WeeklyGridView.DataBind() after you've assigned the SqlDataSource.SelectCommand. Try this:
fruityData.SelectCommand = selectQry
fruityData.DataBind()
I knew it was something stupid. I defined the variables inside of the event handler. I should have done it like this.
Dim appleTotal As Integer = 0
Dim orangeTotal As Integer = 0
Dim bananaTotal As Integer = 0
Dim pearTotal As Integer = 0
Dim grapeTotal As Integer = 0
Dim peachTotal As Integer = 0
Dim cherryTotal As Integer = 0
Dim pineTotal As Integer = 0
Protected Sub WeeklyGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles WeeklyGridView.OnRowDataBound
I apologise if I have posted this before, but I am struggling with this script to push data into Active Directory. The following code works, i.e. it does not produce any errors, but it doesn't update the directory. I have the following code:
<%# Language=VBScript %>
<% response.Buffer = True
'Define the AD OU that contains our users
dim ADUser, user, firstname, lastname, email, telephonenumber, mobile, description
'This initializes all of our variables
user = request.querystring("account_name")
'This puts the value of the account_name into a variable
if len(user) = 0 then
'If the length of the username is equal to 0
response.write "Please supply a username in the query string"
elseif len(user) > 0 then
'Else is length of user is greater than 0
ADUser = "LDAP://OU=RBC Staff,OU=RBC Users,DC=rugby,DC=internal"
' Make AD connection and run query
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\User"
objCon.Properties("Password") = "Password01"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select givenName,sn,mail,telephonenumber,mobile,description, sAMAccountName, cn FROM '"+ ADUser +"' where sAMAccountname='"& user &"'"
Set objRS = objCom.Execute
If IsNull(objRS.Fields("Description").Value) Then
sDesc = ""
else
For Each item In objRS.Fields("description").Value
sDesc = item
Next
end if
if isNull(objRS("givenName")) then
firstname = ""
else
firstname = objRS("givenName")
end if
if isNull(objRS("sn")) then
lastname = ""
else
lastname = objRS("sn")
end if
if isNull(objRS("mail")) then
email = ""
else
email = objRS("mail")
end if
if isNull(objRS("telephonenumber")) then
telephonenumber = ""
else
telephonenumber = objRS("telephonenumber")
end if
if isNull(objRS("mobile")) then
mobile = ""
else
mobile = objRS("mobile")
end if
Response.Write "<form action='editentry.asp?account_name=" & user &"' method='POST'>"
Response.Write "<table>"
Response.Write "<tr>"
Response.Write "<td><label for='firstname'>Firstname</label></td>"
Response.Write "<td><input type='text' id='firstname' value='" + firstname + "' name='firstname'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><label for='lastname'>Lastname</label></td>"
Response.Write "<td><input type='text' id='lastname' value='" & lastname & "' name='lastname'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><label for='email'>E-Mail Address</label></td>"
Response.Write "<td><input type='email' id='email' value='" + email + "' name='email'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><label for='description'>Description</label></td>"
Response.Write "<td><input type='text' id='description' value='" + sDesc + "' name='description'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><label for='mobile'>Mobile</label></td>"
Response.Write "<td><input type='text' name='mobile' value='" + mobile + "' id='mobile'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><label for='telephonenumber'>Telephone Number</label></td>"
Response.Write "<td><input type='text' id='telephonenumber' value='" + telephonenumber + "' name='telephonenumber'></td>"
Response.Write "</tr>"
Response.Write "<tr>"
Response.Write "<td><input type='hidden' name='subval' value='1'></td>"
Response.Write "<td><input type='submit' name='submit''></td>"
Response.Write "</tr>" + vbCrLf
Response.Write "</table>"
Response.Write "</form>"
if request.form("subval")=1 then
'If the subval field equals 1, we know the form has been submitted OK
firstname = request.form("firstname")
lastname = request.form("lastname")
email = request.form("email")
telephonenumber = request.form("telephonenumber")
mobile = request.form("mobile")
Set update = CreateObject("ADODB.Command")
Set update.ActiveConnection = objCon
update.CommandText ="select ADsPath, givenName,sn,mail,telephonenumber,mobile,sAMAccountName FROM '"+ ADUser +"' where sAMAccountname='"& user & "'"
Set update.ActiveConnection = objCon
update.Properties("searchscope") = ADS_SCOPE_ONELEVEL
set writeLDAP = update.Execute
Do While Not writeLDAP.EOF
Set usr = GetObject(writeLDAP.Fields("ADsPath").Value)
usr.Put "gjvenName", firstname
usr.Put "sn", lastname
usr.Put "mail", email
usr.Put "mobile", mobile
usr.Put "telephonenumber", telephonenumber
usr.SetInfo
writeLDAP.MoveNext
loop
response.write "This form has been submitted"
writeLDAP.Close
end if
end if
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCom = Nothing
%>]
The only thing I can think of is that, the login I used wasn't a domain admin account.
I have a gridview in vb.net wich provides a performance value of a list of business names for the previuous week, current week and next week as follows:
LOB W-1 W W+1
--------------------
AMEX 10 15 30
PPR 11 12 14
REM 12 11 10
What I need is for this values to be a hyperlink that opens another window based on the business name and the week to provide further detail. For example, if you want further datail of the value 15 for AMEX and the current week (W) then by pressing the value 15 a new window will open with information for AMEX for the current week.
I have the gridview created but I can not figure out how to do the hyperlinks. Any ideas?
See below code.
<asp:DropDownList ID="DateSelection" runat="server" Height="21px" Width="134px" >
</asp:DropDownList>
<asp:Button ID="Button_Update" runat="server" Text="UPDATE" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
GridLines="None" ForeColor="#333333">
<Columns>
<asp:BoundField DataField="LOB" HeaderText="LOB" />
<asp:BoundField DataField="W-1" HeaderText="W-1" />
<asp:BoundField DataField="W" HeaderText="W" />
<asp:BoundField DataField="W+1" HeaderText="W+1" />
</Columns>
</asp:GridView>
vb code
Dim dv_Groups As New System.Data.DataView
Dim dt_Groups As New System.Data.DataTable
dv_Groups = Group.Select(DataSourceSelectArguments.Empty)
dt_Groups = dv_Groups.ToTable()
Dim dv_Main As New System.Data.DataView
Dim dt_Main As New System.Data.DataTable
dv_Main = SQL_Main.Select(DataSourceSelectArguments.Empty)
dt_Main = dv_Main.ToTable()
Dim dt_Report As New DataTable()
dt_Report.Columns.Add("LOB", Type.GetType("System.String"))
dt_Report.Columns.Add("W-1", Type.GetType("System.String"))
dt_Report.Columns.Add("W", Type.GetType("System.String"))
dt_Report.Columns.Add("W+1", Type.GetType("System.String"))
Dim FindRow() As DataRow
Dim SearchText As String
Dim DateS As Date
Dim DateWeek As String
DateS = DateSelection.SelectedItem.Text
Dateweek = Format(DatePart(DateInterval.WeekOfYear, DateS))
For i As Integer = 0 To dt_Groups.Rows.Count - 1
dt_Report.Rows.Add()
dt_Report.Rows(i)(0) = dt_Groups.Rows(i)(0)
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek - 1 & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(1) = FindRow(0).Item("A_SVL").ToString
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(2) = FindRow(0).Item("A_SVL").ToString
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek + 1 & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(3) = FindRow(0).Item("S_SVL").ToString
Next
GridView1.DataSource = dt_Report
GridView1.DataBind()
Many Thanks
You can use a HyperLinkField or TemplateField to add links to your gridview, as shown here:
https://stackoverflow.com/a/8859655/849182
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?