i have a question to do...
So, i have 2 radiobuttons called "Em Vigor" and "Anulada"
2 radiobutton when i click, they refresh a datatable, and i cant refresh the datatable with my SQL code. I did this:
<form runat="server">
<asp:RadioButton ID="FXvigor" Text="Em Vigor" runat="server" />
<asp:RadioButton ID="FXanulada" Text="Anulada" runat="server" />
</form>
These are the 2 buttons that i have created, and these are 2 if's with SQL commands. But i have search ong google and i cant refresh any of them.
So this is the code:
While FXanulada.Checked = True
FXvigor.Checked = False
If Not Rs.IsClosed Then Rs.Close()
Cmd = New SqlCommand("SELECT tbClientes_Apolices_Bem_Tipos.descrit as tipo, SOURCE.descrit, SOURCE.bem_id, tbClientes_Apolices.apolice_main_id, tbClientes_Apolices.apolice_id, tbClientes_Apolices.apolice_no, tbClientes_Apolices_Tipos.descrit AS apolice_tipo, tbClientes_Apolices.data_inicio, tbClientes_Apolices.data_termo, tbContactos.chave AS seguradora, tbRamos.descrit AS ramo, CASE WHEN nvigor=0 THEN 'Em vigor' WHEN nvigor <> 0 THEN 'Não está em vigor' END AS nvigor_descrit, tbClientes_Apolices.premio_total, SOURCE.tipo_bem_id, SOURCE.apolice_link_id, nvigor FROM (SELECT tbClientes_Apolices_Bem_links.descrit, tbClientes_Apolices_Bem_links.bem_id, tbClientes_Apolices_Bem_links.tipo_bem_id, tbClientes_Apolices.apolice_main_id, MAX(tbClientes_Apolices.apolice_id) as apolice_id, MAX(tbClientes_Apolices_Bem_links.apolice_link_id) as apolice_link_id FROM tbClientes_Apolices_Bem_links LEFT JOIN tbClientes_Apolices ON tbClientes_Apolices_Bem_links.apolice_id = tbClientes_Apolices.apolice_id WHERE tbClientes_Apolices.contacto_id = " & contacto_id.ToString & " GROUP BY tbClientes_Apolices_Bem_links.descrit, tbClientes_Apolices_Bem_links.bem_id, tbClientes_Apolices_Bem_links.tipo_bem_id, tbClientes_Apolices.apolice_main_id ) AS SOURCE LEFT JOIN tbClientes_Apolices ON SOURCE.apolice_id = tbClientes_Apolices.apolice_id LEFT JOIN tbClientes_Apolices_Tipos ON tbClientes_Apolices.tipo_id = tbClientes_Apolices_Tipos.tipo_id LEFT JOIN tbContactos ON tbClientes_Apolices.seguradora_id = tbContactos.contacto_id LEFT JOIN tbSeguradoras_Ramos ON tbClientes_Apolices.ramo_id = tbSeguradoras_Ramos.ramo_id LEFT JOIN tbRamos ON tbSeguradoras_Ramos.ramo_descrit_id = tbRamos.ramo_descrit_id LEFT JOIN tbClientes_Apolices_Bem_Tipos ON SOURCE.tipo_bem_id = tbClientes_Apolices_Bem_Tipos.tipo_bem_id ORDER BY SOURCE.descrit, SOURCE.bem_id, tbClientes_Apolices.data_inicio, tbRamos.descrit", CDSI.SQLServer)
Rs = Cmd.ExecuteReader()
End While
While FXvigor.Checked = True
FXanulada.Checked = False
If Not Rs.IsClosed Then Rs.Close()
Cmd = New SqlCommand("SELECT tbClientes_Apolices.*, tbContactos.chave AS seguradora, tbRamos.ramo_descrit_id, tbRamos.descrit AS ramo, tbClientes_Apolices_Tipos.descrit AS tipo, tmpClientes.nome_union AS cliente, CASE WHEN apolice_no = '' THEN 'PROPOSTA' WHEN apolice_no IS NULL THEN 'PROPOSTA' ELSE apolice_no END AS apolice_no_descrit, CASE WHEN nvigor=0 THEN 'Em vigor' WHEN nvigor<>0 THEN 'Não está em vigor' END AS nvigor_descrit, tbClientes.tipo_id as tipo_cliente_id, risco1.risco, tbClientes_Apolices_Permitions.group_code, tbClientes_Apolices_Permitions.user_code FROM (SELECT MAX(apolice_id) as apolice_id FROM tbClientes_Apolices GROUP BY apolice_main_id) AS A1 LEFT JOIN tbClientes_Apolices ON A1.apolice_id = tbClientes_Apolices.apolice_id LEFT OUTER JOIN tbContactos AS tmpClientes ON tbClientes_Apolices.contacto_id = tmpClientes.contacto_id LEFT OUTER JOIN tbClientes_Apolices_Permitions ON tbClientes_Apolices.apolice_main_id = tbClientes_Apolices_Permitions.apolice_main_id LEFT OUTER JOIN tbClientes ON tbClientes_Apolices.contacto_id = tbClientes.contacto_id LEFT JOIN (SELECT apolice_id, MIN(descrit) as risco FROM tbClientes_Apolices_Bem_Links WHERE predefinido <> 0 GROUP BY apolice_id ) AS Risco1 ON A1.apolice_id = Risco1.apolice_id, tbContactos, tbSeguradoras_Ramos, tbRamos, tbClientes_Apolices_Tipos WHERE tbClientes_Apolices.nvigor <> 0 AND tbClientes_Apolices.ramo_id = tbSeguradoras_Ramos.ramo_id AND tbSeguradoras_Ramos.ramo_descrit_id = tbRamos.ramo_descrit_id AND tbClientes_Apolices.seguradora_id = tbContactos.contacto_id AND tbClientes_Apolices.tipo_id = tbClientes_Apolices_Tipos.tipo_id AND tbClientes_Apolices.contacto_id=" & contacto_id.ToString & " ORDER BY tbClientes_Apolices.data_inicio DESC", CDSI.SQLServer)
Rs = Cmd.ExecuteReader()
End While
To execute code on the server side you need to declare an event handler for your radiobuttons and set the AutoPostBack property to True otherwise the Radiobutton will post their new state only when the page is submitted again
<form runat="server">
<asp:RadioButton ID="FXvigor" Text="Em Vigor" runat="server" AutoPostBack="True"
OnCheckedChanged="FXvigor_CheckedChanged"/>
<asp:RadioButton ID="FXanulada" Text="Anulada" runat="server" AutoPostBack="True"
OnCheckedChanged="FXanulada_CheckedChanged"/>
</form>
Protected Sub FXVigor_CheckedChanged(sender as object,e as System.EventArgs)
if FXVigor.Checked = True Then
....
End If
End Sub
Protected Sub FXanulada_CheckedChanged(sender as object,e as System.EventArgs)
if FXanulada.Checked = True Then
....
End If
End Sub
Related
I have radio button like below
<dx:ASPxRadioButtonList ID="radClaimType" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" ValueType="System.String" Border-BorderStyle="None">
<Items>
<dx:ListEditItem Text="Expenses" Value="1" />
<dx:ListEditItem Text="Travel" Value="2" />
</Items>
</dx:ASPxRadioButtonList>
How do I select/check the radio button based on the value that I have inserted in database ?
Here is my code behind
Dim dt As New Datatable
Dim strSelect As String = "SELECT claim_type FROM detail_table WHERE id = '30'"
Dim myconn As New clsConnection
Try
myconn.OpenConnection()
myconn.FillDataTable(dt, strSelect)
myconn.CloseConnection()
If dt.Rows.Count > 0 Then
If dt.Rows(0).Item("claim_type") = 1 Then
radClaimType.SelectedIndex = 1
ElseIf dt.Rows(0).Item("claim_type") = 2 Then
radClaimType.SelectedIndex = 2
End If
radClaimType.Enabled = False
End If
Catch ex As Exception
MsgBox("Error")
myconn.CloseConnection()
End Try
The result is like this which is incorrect because the claim_type value for id = '30' is 1 which is Expense. I have debug the code and the value for claim_type is indeed 1 but the radio button does not checked/selected to Expense. How do I correct this ?
You should tag what 3rd party control library you are using here.
Anyway, as a general rule, the asp.net RB-list can be set by "index", starting at 0, or you can set by value.
So, for your code, then this:
radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
You do NOT want to set by index, since the RB list could have ANY values, and
0 = first one
1 = 2nd one
etc. etc. etc.
So, index starts at 0
but, you want to set the RB by "value", and hence:
radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
You can check your documentaton for that control (I don't have it).
But, you don't need a "if/then" here. You can set the value of the RB, and it should then select/display the value corectly
so with this:
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
RepeatDirection="Horizontal" AutoPostBack="true" >
<asp:ListItem Value="100">Expenses</asp:ListItem>
<asp:ListItem Value="200">Travel</asp:ListItem>
</asp:RadioButtonList>
Then I can set 0 (first) or 1 (second) using "indexing" like this:
RadioButtonList1.SelectedIndex = 0 ' would select the 100
RadioButtonList1.SelectedIndex = 1 ' would select the 200
Or, by value
RadioButtonList1.SelectedValue = 100 ' would select the first one
SOLUTION FOR FUTURE REFERENCE
Problem was the "tecnico" variable that became 0 at every postback, also to avoid any problem I get rid of global variables data1 and data2 and moved them inside the Bindrepeater routine, like this:
Dim data1, data2 As DateTime
If Len(ViewState("dataDa")) = 0 Then
data1 = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
data2 = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
ViewState("dataDa") = data1
ViewState("dataA") = data2
Else
data1 = Date.ParseExact(ViewState("dataDa"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(ViewState("dataA"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
End If
ORIGINAL QUESTION
I'm having trouble with databind of a repeater on page load. I would make a sort of weekly calendar, so the repeater should show dates and for every day a nested repeater should show appointments. I made a simple week selector with a Previous/Next button to move through weeks. It work fine on first page load, but it shows nothing when I use the buttons to change active week.
I know the problem is the postback for sure, but I can't get around this... any help?
html:
<div id="divCalendario" class="panel" runat="Server">
<div id="divCalendarNavigator" style="display: block;" runat="server">
<div>
<%--<asp:Calendar runat="server" ID="calendar" SelectionMode="DayWeek" TitleStyle-ForeColor="#1f7872" TitleStyle-Font-Bold="true" PrevMonthText="<i class=icon-foo></i>" NextMonthText="<i class=icon-foo></i>" NextPrevStyle-Font-Names="FontAwesome" SelectWeekText="<i class=icon-foo></i>" SelectorStyle-Font-Names="FontAwesome" WeekendDayStyle-BackColor="LightGray" SelectedDayStyle-BackColor="#f3ef98" SelectedDayStyle-ForeColor="Black" SelectedDayStyle-Font-Bold="true" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>--%>
<asp:LinkButton runat="server" ID="lnkPrevWeek" OnClick="lnkPrevWeek_Click"><i class="fa fa-arrow-circle-o-left" aria-hidden="true"></i></asp:LinkButton>
<asp:Literal ID="litData" runat="server"></asp:Literal>
<asp:LinkButton runat="server" ID="lnkNextWeek" OnClick="lnkNextWeek_Click"><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></asp:LinkButton>
<asp:HiddenField runat="server" ID="hdnDa" /><asp:HiddenField runat="server" ID="hdnA" /><asp:HiddenField runat="server" ID="hdnSpostamento"/>
<asp:DropDownList ID="ddlTecnicoCal" runat="server" AppendDataBoundItems="true" CssClass="tendina" placeholder="Tecnico" AutoPostBack="true">
<%--<asp:ListItem Value="-1">Tutti</asp:ListItem>--%>
</asp:DropDownList>
</div>
</div>
<asp:Repeater ID="rptParent" runat="server">
<ItemTemplate>
<p style="margin-left: 10px"><b>
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "data", "{0:dd/MM/yyyy}")%>'></asp:Label></b></p>
<asp:Repeater ID="rptAppuntamenti" runat="server">
<ItemTemplate>
<%# Eval("id")%></td>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
CODE:
Imports System.Data.SqlClient
Imports System.Globalization
Public Class Calendario
Inherits System.Web.UI.Page
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Public Function GetDayFromWeek(week As DateTime, day As DayOfWeek) As DateTime
Dim startDay As DayOfWeek = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek
' get the beginning of the week
Dim diff As Integer = CInt(week.DayOfWeek) - CInt(startDay)
Dim beginingOfWeek As DateTime = week.AddDays(diff * -1)
' get the day we are looking for
diff = CInt(day) - CInt(startDay)
If diff < 0 Then
diff = 7 - CInt(startDay)
End If
Return beginingOfWeek.AddDays(diff)
End Function
Public Function datasql(ByVal dataini As Date) As String
Return dataini.Year & "-" & dataini.Month & "-" & dataini.Day
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
caricaTecnici()
Dim monday = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
Dim sunday = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
Dim dbVulcano As New dbVulcanoEntities
data1 = Date.ParseExact(monday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(sunday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
tecnico = Session("idUtente")
utente = dbVulcano.Utenti.Where(Function(u) u.IDUtente = tecnico).Single
End If
BindRepeater()
End Sub
Private Sub BindRepeater()
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select distinct(statoRic.DataAss) as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null and statoric.DataAss between #data1 and #data2 And RFTecnico=#tecnico
group by statoRic.DataAss order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data1", data1)
cmd.Parameters.AddWithValue("#data2", data2)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
rptParent.DataSource = dt
rptParent.DataBind()
End Using
End Using
End Using
End Sub
Private Sub rptParent_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptParent.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim childRepeater As Repeater = e.Item.FindControl("rptAppuntamenti")
Dim lblDate As Label = e.Item.FindControl("lblDate")
'Dim lblTecnico As Label = e.Item.FindControl("lblTecnico")
Dim data As DateTime = Date.ParseExact(lblDate.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
'lblTecnico.Text = utente.NomeExt
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select statoric.id, (case when clienti.IDCliente = 796 then richieste.descr else clienti.RagSociale end) as RagSociale, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraDalle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraDalle % 100)),'00:00') as eventstart, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraAlle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraAlle % 100)),'00:30') as eventend, Utenti.Nome as tecnico, statoRic.DataAss as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null And RFTecnico=#tecnico and statoric.DataAss = #data
order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data", data)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childRepeater.DataSource = dt
childRepeater.DataBind()
End Using
End Using
End Using
End If
End Sub
Sub caricaTecnici()
Dim Query As String = "SELECT nome,idutente FROM Utenti WHERE attivo=1"
Dim cmd As New SqlCommand(query)
ddlTecnicoCal.DataSource = GetData(cmd)
ddlTecnicoCal.DataTextField = "nome"
ddlTecnicoCal.DataValueField = "idutente"
ddlTecnicoCal.DataBind()
ddlTecnicoCal.SelectedIndex = ddlTecnicoCal.Items.IndexOf(ddlTecnicoCal.Items.FindByValue(Session("idUtente")))
End Sub
Private Function GetData(cmd As SqlCommand) As DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Using con As New SqlConnection(strConnString)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Protected Sub lnkPrevWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(-7)
Dim sunday = data2.AddDays(-7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
Protected Sub lnkNextWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(7)
Dim sunday = data2.AddDays(7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
End Class
Thanks!
I think your problem could be your global variables not preserving their new value after postback:
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Try to store the values inside Session variables or Viewstate instead.
For example:
Session("tecnico") = x
ViewState("utente") = y
I've had this issue in the past.
The global variable doesn't keep its value
My Public Class is Below:
public class GlobalVariable
public shared listbox2Count = listbox2.items.count
public shared containsListbox2Item
End Class
my code where i assign a text item to a variable object:
Public Function getListBoxText()
If ListBox2.Text = "X,Y Coordinate" Then
GlobalVariable.containsListBox2Item = "X,Y Coordinate"
ElseIf ListBox2.Text = "Latitude, Longitude" Then
GlobalVariable.containsListBox2Item = "Latitude, Longitude"
Return Nothing
End Function
My code where i am stuck is below:
Dim dt As New DataTable
dt.Clear()
For i As Integer = 0 To GlobalVariable.listbox2Count - 1
If GlobalVariable.containsListBox2Item(i) = "X,Y Coordinate" Then
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
ElseIf GlobalVariable.containsListBox2Item(i) = "Latitude, Longitude" Then
If (Not dt.Columns.Contains("Latitude")) Then dt.Columns.Add("Latitude")
If (Not dt.Columns.Contains("Longitude")) Then dt.Columns.Add("Longitude")
End If
Next
Dim mr As DataRow
mr = dt.NewRow
mr("X Coordinate") = "203910"
mr("Y Coordinate") = "190280"
mr("Latitude") = "100022"
mr("Longitude") = "201999"
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
I am absolutely not sure whats wrong with this code and if someone can help me or correct it for me would be great help Thanks. I want to add all four columns into the grid view. and then keep adding more and more columns using else if.
Try this, its extensive but it does work, it displays all the values you have on listbox2
Dim i As Integer
Dim dt As New DataTable
Dim Card As String = ""
Dim Geo As String = ""
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text = "X,Y Coordinate" Then
If Card = "ok" Then
Else
dt.Columns.Add("X Coordinate")
dt.Columns.Add("Y Coordinate")
Card = "ok"
End If
ElseIf ListBox2.Items.Item(i).Text = "Latitude, Longitude" Then
If Geo = "ok" Then
Else
dt.Columns.Add("Latitude")
dt.Columns.Add("Longitude")
Geo = "ok"
End If
End If
Next
Dim mr As DataRow
For i = 0 To ListBox2.Items.Count - 1
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(0).ToString.Substring(0, 1)) Then
If dt.Columns.Item(0).ToString = "Latitude" Then
mr = dt.NewRow
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(0).ToString = "X Coordinate" Then
mr = dt.NewRow
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
If ListBox2.Items.Item(i).Text.Contains(dt.Columns.Item(2).ToString.Substring(0, 1)) Then
If dt.Columns.Item(2).ToString = "Latitude" Then
mr("Latitude") = "100909"
mr("Longitude") = "1002929"
ElseIf dt.Columns.Item(2).ToString = "X Coordinate" Then
mr("X Coordinate") = "909090"
mr("Y Coordinate") = "109209"
End If
End If
Dim res As Integer
res = i Mod 2
If res > 0 Or i = ListBox2.Items.Count - 1 Then
dt.Rows.Add(mr)
GridView1.DataSource = dt
GridView1.DataBind()
End If
Next
Simple Form that defines a GridView by using the contents of a ListBox to provide Column Information
Important I've altered the ListBox Values to represent Column Headers. See why below.
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox2" runat="server">
<asp:ListItem Text="X,Y Coordinate" Value="X Coordinate, Y Coordinate" />
<asp:ListItem Text="Latitude, Longitude" Value="Latitude, Longitude" />
</asp:ListBox>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
EmptyDataText="No Data" ShowHeader="true">
</asp:GridView>
</div>
</form>
Code Behind
Public Class WebForm1
Inherits System.Web.UI.Page
' DataTable Name and Application Cache Key
Const DataTableCacheKey As String = "CoordinatesDataTable"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Create the Table and add to Cache, only once
If Not Page.IsPostBack Then
CreateDataTableFromListView()
End If
GridView1.DataSource = Cache(DataTableCacheKey)
GridView1.DataBind()
End Sub
Create the DataSource
NOTE: By using the Value Property of the ListItem as a comma separated list of strings, you can associate multiple columns to a given Coordinate system. Note this is not the ideal way because there is no way set up a data type, I'm assuming everything is a Double value. Still it's far better than a long string of If conditions to determine columns and headers.
' All the magic happens here...
Private Sub CreateDataTableFromListView()
' Instantiate a DataTable with a table name
Dim dt As New DataTable(DataTableCacheKey)
' Loop throught the ListBox and...
For Each li As ListItem In ListBox2.Items
' Split each Value Property into an array
' of strings to use as Column identifiers
Dim ColumnHeaders() As String = li.Value.Split(",")
' Loop through the array of strings to create
' DataTable Columns
For Each ch As String In ColumnHeaders
dt.Columns.Add(ch, GetType(Double))
Next
Next
' Add an initial Blank Row
Dim row As DataRow = dt.NewRow()
' Loop Through Columns and set a default
' value of 0 for each column
For Each c As DataColumn In dt.Columns
row(c.ColumnName) = 0
Next
' Add the Row to the Table
dt.Rows.Add(row)
' Persist the DataTable to the Application cache
Cache(DataTableCacheKey) = dt
End Sub
End Class
My apologies up front for the long thread.
I am very flabbergasted as to why this code is not working correctly.
Please have a look.
On markup,
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="cancelBtn" style="width:105px;padding:5px;margin:5px;" runat="server" CommandName="delete" OnDataBinding="btnDelete_DataBinding" OnClientClick='return confirm("Are you sure you want to delete this entry?");' Text="Cancel Training" />
</ItemTemplate>
</asp:TemplateField>
Then I have a function called getDateDifference() As Boolean with code below:
Private Function getDateDifference() As Boolean
Dim username = Session("Username")
Dim myConnectionString As [String] = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim cmd1 As New SqlCommand("select DateDiff(dd,GetDate(),d.trainingDates) as DaysCount " & _
"from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
"Inner Join tblLocations l on t.locationId = l.LocationId " & _
"Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
"Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
"Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
"Inner Join tblLogin lg on t.username = lg.username where lg.username = #username", myConnection)
cmd1.Parameters.AddWithValue("#username", username)
Dim dr1 As SqlDataReader = cmd1.ExecuteReader()
If dr1.Read() Then
Dim DaysCount As Integer = dr1("DaysCount")
Response.Write(DaysCount)
If DaysCount >= 2 Then
Return True
Else
Return False
End If
End If
Return False
End Function
The function is invoked below:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim btn As Button = DirectCast(e.Row.FindControl("cancelBtn"), Button)
btn.Enabled = Not getDateDifference()
End If
End Sub
All we trying do to is compare trainingdates with current date.
If current date is within 24 hours (or 2 days) of training date, a user who has already signed up for a class, cannot cancel that class.
The user can cancel if current date is more than 2 days before training date.
To test, I have 2 trainings scheduled on my account.
One training date is 6/22/2013
The other training date is 6/29/2013.
When I run the query above, I get 1, and 8 days respectively.
This is correct because today's date is 6/21/2013 which is there is one day left before first training date of 6/22/2013 and 8 days left
before the second training date of 6/29/2013.
This means that on my app (please see screenshot), I expect to see one button disabled and the other enabled.
![enter image description here][1]
As you can see from screenshot, this is not happening. Both are either getting enabled or disabled no matter what the training date is.
When I try to debug DaysCount with response.write (DaysCount), it shows 11.
Not sure how this is happening. It has been at least 3 days since I have been struggling with this.
DB is sql server 2005. However production db is 2008.
Thanks in advance for your assistance.
I'm not sure what is happening here, but to try and debug it I would just return d.trainingDates from your database query instead of doing the DateDiff, and then do this to validate it:
If dr1.Read() Then
Dim trngDate As Date = dr1("trainingDates")
Response.Write(trngDate.ToString)
If (trngDate - DateTime.Now).TotalDays >= 2 Then
Return True
Else
Return False
End If
End If
EDIT
But - why not just compare the dates in the RowDataBound event.
There is no need to perform another query, the date your are comparing is in the row you are binding
Something like this (untested) code:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dateValue As Date = Date.Parse(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Dates")))
Dim btn As Button = DirectCast(e.Row.FindControl("cancelBtn"), Button)
btn.Enabled = (dateValue - DateTime.Now).TotalDays >= 2
End If
End Sub
I know you accepted #Matt Wilko's answer, but just to answer the specific problem you're facing:-
The problem is that your query returns all tblTraining records for the user. There is no condition in the where clause to determine which tblTraining record is the current active one.
Response.Write(DaysCount) did not produce 11, but rather produced 1 and 1, which is the difference between 6/22/2013 and 6/21/2013. You had 2 rows, so each digit must have been for a different row, and both rows seems to be getting the same date difference.
You will probably need to declare Private Function getDateDifference(courseId as Integer) As Boolean or something similar, so that you can pass the courseId to the function and use it in your SQL statement to identify the specific training program that you want. Probably your SQL statement will look something like
Dim cmd1 As New SqlCommand(_
"select DateDiff(dd,GetDate(),d.trainingDates) as DaysCount " & _
"from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
"Inner Join tblLocations l on t.locationId = l.LocationId " & _
"Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
"Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
"Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
"Inner Join tblLogin lg on t.username = lg.username " & _
"where lg.username = #username and " & _
"t.courseId = #courseId", myConnection)
cmd1.Parameters.AddWithValue("#courseId", courseId)
As to where you can get your courseId, you can probably use the approach #Matt Wilko used. But then again, his method would have avoided this whole issue altogether.
This is my code and i am getting an error ..Cannot have multiple items selected in a DropDownList. when the page loads it select "ALL" in DDLModality but when i change DDLModality.selectedvalue to any "value" then no error but again when i change to "ALL "getting the error.
onchange of DDLMODALITY submit the form
form1.target = "";
form1.action = "";
form1.submit();
' USED TO ADD REFERRING PHYSICIAN IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '')"
Else
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '') And Center_ID = " & Session("CenterID")
End If
objDS = objFun.RunQuery(sql)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
cboRefPhy.Items.Add(Li1)
' USED TO COUNT THE STUDIES IN THE DROPDOWN
If (objDS.Tables(0).Rows.Count <> 0) Then
' USED TO CIRCULATE LOOP UPTO THE RECORD COUNT
Dim i As Integer
For i = 0 To objDS.Tables(0).Rows.Count - 1
' USED TO CREATE NEW ITEM IN THE DROPDOWN
Dim Li As New ListItem
Li.Text = objDS.Tables(0).Rows(i)("Name").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Ref_Phy_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
cboRefPhy.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
cboRefPhy.ClearSelection()
cboRefPhy.SelectedValue = Convert.ToString(Request.Form("cboRefPhy"))
'USED TO ADD MODALITY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
'Dim objDS As New DataSet()
objDS = objFun.RunQuery(sqlStudy)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
'Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
' Dim all As String
' all = "All"
'Ddl_Modality.Items.Add(all)
DDLModality.Items.Add(Li1)
' USED TO COUNT THE STUDIES IN THE DROPDOWN
If (objDS.Tables(0).Rows.Count <> 0) Then
' USED TO CIRCULATE LOOP UPTO THE RECORD COUNT
Dim i As Integer
For i = 0 To objDS.Tables(0).Rows.Count - 1
' USED TO CREATE NEW ITEM IN THE DROPDOWN
Dim Li As New ListItem
Li.Text = objDS.Tables(0).Rows(i)("Modality").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Modality_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
DDLModality.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
DDLModality.ClearSelection()
DDLModality.SelectedValue = Convert.ToString(Request.Form("DDLModality"))
' USED TO ADD STUDY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
If (DDLModality.SelectedItem.Text <> "ALL") Then
sqlStudy = sqlStudy & " AND Modality = '" & DDLModality.SelectedItem.Text & "'"
End If
try
DDLModality.ClearSelection()
before setting DDLModality.SelectedValue
Dim Li2 As New ListItem()
Li2.Text = "ALL"
Li2.Value = ""
DDLModality.Items.Add(Li2)
I was facing the same problem. If you add one defined ListItem (in this case Li1) to two or more dropdownlists, this error will occur while assigning selectedvalue to any dropdownlist.
Simple solution is define separate ListItems for separate dropdownlists like Li1, Li2, Li3, etc.
Don't understand the logic behind, but it works!