Get checkbx values selected from database - asp.net

I have users form in which they can select some values from checkbox list & values selected in that stores in database in li form. Now I want when users wants to update their form they should be able to see the values checked they have selected earlier.
here is my code.
Insert Form
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
selectedServices &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO hospitals (`hospitalID`,`username`, `password`) values ('" + ID + "', '"selectedServices.ToString + "', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
On User Profile page after login they should be able to see what options they have selected. Hence there is a option for users to update their details again
UPDATED
User Profile Page
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "SELECT * FROM hospitals WHERE username='" + Server.HtmlEncode(Request.Cookies("chkusername").Value) + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
Dim lblservice As New Label
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
lblservice.Text = String.Concat(lblservice.Text + ",", chk.Value)
End If
Next
da.Fill(dt)
con.Close()
TextId.Text = dt.Rows(0)("hospitalID").ToString
Catch ex As Exception
Response.Write(ex)
End Try
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Private Sub updateInfo_Click(sender As Object, e As EventArgs) Handles updateInfo.Click
Try
Dim con As New MySqlConnection
Dim query As New MySqlCommand
con.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
query.Connection = con
con.Open()
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If selectedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.Selected = True
End If
Next
query.CommandText = "UPDATE hospitals SET name = '" + businessName.Text + "', contactPerson = '" + contactPerson.Text + "', websiteName = '" + websiteName.Text + "', email = '" + emailName.Text + "', phone1 = '" + phone1.Text + "', phone2 = '" + phone2.Text + "', mobileNumber = '" + mobile.Text + "', buildingName = '" + buildingName.Text + "', streetName = '" + address.Text + "', landmark = '" + landmark.Text + "', areaName = '" + areaName.Text + "', city = '" + suburb.Text + "', state = '" + state.Text + "', zipCode = '" + zip.Text + "', overview = '" + overview.Text + "', registration = '" + regNo.Text + "', establishment = '" + foundation.Text + "', founder = '" + founderName.Text + "', generalBed = '" + GeneralBeds.Text + "', icuBed = '" + ICU.Text + "', consultancyFees = '" + consultinfees.Text + "', mondayFrom = '" + mondayFrom.Text + "', mondayTo = '" + mondayTo.Text + "', tuesdayFrom = '" + tuesdayFrom.Text + "', tuesdayTo = '" + tuesdayTo.Text + "', wednesdayFrom = '" + wedFrom.Text + "', wednesdayTo = '" + wedTo.Text + "', thursdayFrom = '" + thursdayFrom.Text + "', thursdayTo = '" + thursdayTo.Text + "', fridayFrom = '" + fridayFrom.Text + "', fridayTo = '" + fridayTo.Text + "', saturdayFrom = '" + saturdayFrom.Text + "', saturdayTo = '" + saturdayTo.Text + "', sundayFrom = '" + sundayFrom.Text + "', sundayTo = '" + sundayTo.Text + "', visitFrom = '" + visitFrom.Text + "', visitTo = '" + visitTo.Text + "', bestKnownFor = '" + bestknowFor.Text + "' WHERE hospitalID = '" + TextId.Text + "'"
query.ExecuteNonQuery()
con.Close()
Response.Write("<script language='javascript'>alert('Information updated successfully.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub

Please check below,
'Here I assume that, you will call PopulateServices to populate servicesList checkbox list
PopulateServices()
'You didn't mention fieldName, so I assume that field in database is :
'savedServices - This will be li tags like, <li>item 1</li><li>item 2</li>
'Now loop through all items within checkbox list
For Each chk As ListItem In servicesList.Items
'You need to check whether this item saved in database or not?
'If item already saved in database, display as selected
If savedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.selected = true
End If
Next

Related

ASP .NET Forms and Submit

I am new to ASP .Net Web Forms. Tried creating a Web Page going through Youtube Tutorials and now I'm stuck on this step where I have created a form with inputs and select using Bootstrap. Here is what my Frontend looks like which is in Default.aspx ---->
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron">
<center class="form-group-lg">
<form method="post" action="btnShow_Click">
<label>Token Number</label>
<input type="text" name="txtCommand" id="txtCommand" class="text-center form-control" value="" runat="server" />
<div class="row form-group">
<div class="col-md-4">
<label>Room Number</label>
<select class="form-control" name="CounterID" id="CounterID" runat="server">
<option value="0">Select Room Number</option>
<option value="1">Room Number 01</option>
<option value="2">Room Number 02</option>
<option value="3">Room Number 03</option>
<option value="4">Room Number 04</option>
<option value="5">Room Number 05</option>
<option value="6">Room Number 06</option>
<option value="7">Room Number 07</option>
<option value="8">Room Number 08</option>
<option value="9">Room Number 09</option>
<option value="10">Room Number 10</option>
</select>
</div>
<div class="col-md-4">
<label>Department</label>
<select class="form-control" id="CounterName" name="CounterName" runat="server">
</select>
</div>
<div class="col-md-4">
<label>Terminal</label>
<input type="text" class="form-control" name="TerminalID" id="TerminalID" runat="server" value="000" />
</div>
</div>
<div class="row">
<div class="col-md-6">
<p>Waiting Patients: <span id="label2">100</span></p>
<!-- <input type="text" readonly name="" id="label2" class="form-control" runat="server" value=""/> -->
</div>
<div class="col-md-6">
<p>Total Patients: <span id="label1">100</span></p>
<!-- <input type="text" readonly name="label1" id="label1" class="form-control" runat="server" value=""/> -->
</div>
</div>
<div class="form-group" style="margin-top:15px;">
<asp:Button ID="btnShow" type="submit" runat="server" Text="Next" Width="56px"/>
</div>
</form>
</center>
</div>
</asp:Content>
and my Default.aspx.cs looks like --->>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
string depart = "select DeptCode, DepartmentName from Que_Master_Department where Active = 1";
SqlDataAdapter sda = new SqlDataAdapter(depart, sqlconn);
sqlconn.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
CounterName.DataSource = dt;
CounterName.DataTextField = "DepartmentName";
CounterName.DataValueField = "DepartmentName";
CounterName.DataBind();
sqlconn.Close();
btnShow.Click += btnShow_Click;
}
//Recall Button Commands Start Here
private void Recall_Click(object sender, EventArgs e)
{
CalcPatientRemain();
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
string query = " DELETE FROM Que_Delegation WHERE Token = '" + txtCommand.Value + "'";
SqlCommand scom = new SqlCommand(query, sqlconn);
sqlconn.Open();
scom.ExecuteNonQuery();
query = " INSERT INTO Que_Delegation (Token, TerminalID, CounterID, CounterName, Dispatch) VALUES ('" + txtCommand.Value + "','" + TerminalID + "','" + CounterID + "','" + CounterName + "','False')";
SqlCommand scom1 = new SqlCommand(query, sqlconn);
scom1.ExecuteNonQuery();
sqlconn.Close();
}
//Recall Button Commands Ended
//Next Button Commands Starts
protected void Next_Click(object Sender, EventArgs e)
{
GetToken();
CalcPatientRemain();
MainScreenDisplay();
}
public void GetToken()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
String userqry = "SELECT TOP(1) Token, ID FROM Que_Management2 Where Department = '" + CounterName + "' AND Flag = 'False' ORDER BY ID ASC";
sqlconn.Open();
SqlCommand cmd = new SqlCommand(userqry, sqlconn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
txtCommand.Value = dr[0].ToString();
}
}
else
{
txtCommand.Value = string.Empty;
}
dr.Close();
string query = "Update Que_Management2 SET Flag = 'True' WHERE Token = '" + txtCommand.Value + "'";
SqlCommand scom2 = new SqlCommand(query, sqlconn);
scom2.ExecuteNonQuery();
if (txtCommand.Value != "")
{
query = " DELETE FROM Que_Delegation";
SqlCommand scom3 = new SqlCommand(query, sqlconn);
scom3.ExecuteNonQuery();
query = " INSERT INTO Que_Delegation (Token, TerminalID, CounterID, CounterName, Dispatch) VALUES ('" + txtCommand.Value + "','" + TerminalID + "','" + CounterID + "','" + CounterName + "','False')";
SqlCommand scom4 = new SqlCommand(query, sqlconn);
scom4.ExecuteNonQuery();
}
sqlconn.Close();
}
catch (Exception ex)
{
string abc = ex.Message;
}
}
public void CalcPatientRemain()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
DateTime Date1 = DateTime.Today;
DateTime Date2 = DateTime.Today.AddDays(1);
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand("usp_GetPatientRemain", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = Date1;
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = Date2;
cmd.Parameters.Add("#Department", SqlDbType.NVarChar).Value = CounterName;
dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
label2.Value = (dr[0].ToString());
}
}
dr.Close();
cmd = new SqlCommand("usp_GetPatientTotal", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = Date1;
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = Date2;
cmd.Parameters.Add("#Department", SqlDbType.NVarChar).Value = CounterName;
dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
label1.Value = (dr[0].ToString());
}
}
dr.Close();
sqlconn.Close();
}
catch (Exception ex)
{
string abc = ex.Message;
}
}
public void MainScreenDisplay()
{
string conn = ConfigurationManager.ConnectionStrings["GIMS_HIMS"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(conn);
sqlconn.Open();
string Date = DateTime.Now.ToString("MM/dd/yyyy");
string query = "";
if (txtCommand.Value == "" || txtCommand.Value == null)
{
txtCommand.Value = "----";
}
if (CounterID.Value == "1")
{
query = "Update Que_MainScreenDelegate2 SET T1 = '" + txtCommand.Value + "', C1 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom5 = new SqlCommand(query, sqlconn);
scom5.ExecuteNonQuery();
}
else if (CounterID.Value == "2")
{
query = "Update Que_MainScreenDelegate2 SET T2 = '" + txtCommand.Value + "', C2 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom6 = new SqlCommand(query, sqlconn);
scom6.ExecuteNonQuery();
}
else if (CounterID.Value == "3")
{
query = "Update Que_MainScreenDelegate2 SET T3 = '" + txtCommand.Value + "', C3 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom7 = new SqlCommand(query, sqlconn);
scom7.ExecuteNonQuery();
}
else if (CounterID.Value == "4")
{
query = "Update Que_MainScreenDelegate2 SET T4 = '" + txtCommand.Value + "', C4 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom8 = new SqlCommand(query, sqlconn);
scom8.ExecuteNonQuery();
}
else if (CounterID.Value == "5")
{
query = "Update Que_MainScreenDelegate2 SET T5 = '" + txtCommand.Value + "', C5 = '" + CounterID + "' , CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom9 = new SqlCommand(query, sqlconn);
scom9.ExecuteNonQuery();
}
else if (CounterID.Value == "6")
{
query = "Update Que_MainScreenDelegate2 SET T6 = '" + txtCommand.Value + "', C6 = '" + CounterID + "' , CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom10 = new SqlCommand(query, sqlconn);
scom10.ExecuteNonQuery();
}
else if (CounterID.Value == "7")
{
query = "Update Que_MainScreenDelegate2 SET T7 = '" + txtCommand.Value + "', C7 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom11 = new SqlCommand(query, sqlconn);
scom11.ExecuteNonQuery();
}
else if (CounterID.Value == "8")
{
query = "Update Que_MainScreenDelegate2 SET T8 = '" + txtCommand.Value + "', C8 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom12 = new SqlCommand(query, sqlconn);
scom12.ExecuteNonQuery();
}
else if (CounterID.Value == "9")
{
query = "Update Que_MainScreenDelegate2 SET T9 = '" + txtCommand.Value + "', C9 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom13 = new SqlCommand(query, sqlconn);
scom13.ExecuteNonQuery();
}
else if (CounterID.Value == "10")
{
query = "Update Que_MainScreenDelegate2 SET T10 = '" + txtCommand.Value + "', C10 = '" + CounterID + "', CMain = '" + CounterID + "', TMain = '" + txtCommand.Value + "', Sound = 'YES' WHERE Date = '" + Date + "'";
SqlCommand scom14 = new SqlCommand(query, sqlconn);
scom14.ExecuteNonQuery();
}
}
//Next Button Commands Ended
protected void btnShow_Click(object Sender, EventArgs e)
{
// Page.ClientScript.RegisterStartupScript(
//Page.GetType(),
//"MessageBox",
//"<script language='javascript'>alert('Hello');</script>"
//);
GetToken();
CalcPatientRemain();
MainScreenDisplay();
}
}
}
The problem I'm facing is its doing nothing. No changes are visible and the database also shows no updates. The button works when I trigger OnClick event on it as show in the commented function where I was showing a message on button click but same when I try my functions its not working. Can someone please help what I'm doing wrong.
Dump this tutorial immediately. It teaches you an outdated framework (WebForms is not maintained anymore and won't run on .NET 5), and worse, it has giant SQL injection vulnerabilities (despite using parameterized queries - sometimes). Seriously, tutorials like this should be pulled.
If you want to create a .NET web application in 2021, use ASP.NET Core MVC or Razor Pages.
As for your error, you don't bind the Recall_Click handler to any button.

VB.Net GridView Table with paging, on PageIndexChanging event displays nothing or first page again

I am trying to display data queried from Oracle in a grid view and have added paging with a PageIndexChanging event. However, after a few different tries with small changes, clicking another page either displays screen with no grid view or just refreshes site with gridview still on page 1. Never worked with web apps/sites before, any ideas?
Code:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
Dim con As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim commandstr As String
Dim wherestr As String
Dim dt As DataTable = New DataTable
Dim oda As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
'Remove any non-aplhanumeric characters from the input string
MeterID_tb.Text = Regex.Replace(MeterID_tb.Text, "[^A-Za-z0-9]+", "")
'Opco_tb.Text = Regex.Replace(Opco_tb.Text, "[^A-Za-z0-9]+", "")
DateFrom_tb.Text = Regex.Replace(DateFrom_tb.Text, "[^A-Za-z0-9]+", "")
DateTo_tb.Text = Regex.Replace(DateTo_tb.Text, "[^A-Za-z0-9]+", "")
'Don't allow the user to search without a filter. The results returned will be too large
'Opco_tb.Text = "" &
If (MeterID_tb.Text = "") And (Division_db.SelectedValue = "Any") And (DateFrom_tb.Text = "") And (DateTo_tb.Text = "") Then
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & "You must enter at least one search parameter." & """);"
strScript += "</script>"
If (Not Page.IsStartupScriptRegistered("clientScript")) Then
Page.RegisterStartupScript("clientScript", strScript)
End If
Exit Sub
End If
con = New OleDb.OleDbConnection(*Hidden*)
commandstr = "SELECT METERID as ""Meter ID"", REPID as ""Rep ID"", DIVISION as ""Division"", CITY as ""City"", ADDRESS as ""Address"", RATECODE as ""Ratecode"", METERFORM as ""Meter Form"", METERSTATUS as ""Meter Status"", METERPOINTSTATUS as ""Meter Point Status"", BILLINGCYCLE as ""Billing Cycle"", FILENAME as ""Filename"", FILEDATETIME as ""File Date/Time"" from BAD_METER_LIST"
wherestr = " WHERE"
If MeterID_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " METERID = '" + MeterID_tb.Text + "'"
Else
wherestr = wherestr + " AND METERID = '" + MeterID_tb.Text + "'"
End If
End If
If Division_db.SelectedValue <> "Any" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " DIVISION = " + Division_db.SelectedValue
Else
wherestr = wherestr + " AND DIVISION = " + Division_db.SelectedValue
End If
End If
If DateFrom_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
End If
End If
If DateTo_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
End If
End If
command = New OleDb.OleDbCommand(commandstr + wherestr)
command.Connection = con
con.Open()
oda.SelectCommand = command
oda.Fill(dt)
Me.Grid_Bad_Meters.DataSource = dt
Me.Grid_Bad_Meters.DataBind()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Grid_Bad_Meters_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles Grid_Bad_Meters.PageIndexChanging
'Grid_Bad_Meters.Visible = True
Grid_Bad_Meters.PageIndex = e.NewPageIndex
Grid_Bad_Meters.DataBind()
End Sub
End Class
You need to rebind the GridView upon changing PageIndex.
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
#Region "Subs"
Private Sub CleanInput()
'Remove any non-aplhanumeric characters from the input string
MeterID_tb.Text = Regex.Replace(MeterID_tb.Text, "[^A-Za-z0-9]+", "")
'Opco_tb.Text = Regex.Replace(Opco_tb.Text, "[^A-Za-z0-9]+", "")
DateFrom_tb.Text = Regex.Replace(DateFrom_tb.Text, "[^A-Za-z0-9]+", "")
DateTo_tb.Text = Regex.Replace(DateTo_tb.Text, "[^A-Za-z0-9]+", "")
End Sub
Private Sub RequireFilter
'Don't allow the user to search without a filter. The results returned will be too large
'Opco_tb.Text = "" &
If ((MeterID_tb.Text = "")
AndAlso (Division_db.SelectedValue = "Any")
AndAlso (DateFrom_tb.Text = "")
AndAlso (DateTo_tb.Text = "")) Then
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & "You must enter at least one search parameter." & """);"
strScript += "</script>"
If (Not Page.IsStartupScriptRegistered("clientScript")) Then
Page.RegisterStartupScript("clientScript", strScript)
End If
Exit Sub
End If
End Sub
Private Sub FillGridView
Dim con As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim commandstr As String
Dim wherestr As String
Dim dt As DataTable = New DataTable
Dim oda As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
con = New OleDb.OleDbConnection(*Hidden*)
commandstr = "SELECT METERID as ""Meter ID"", REPID as ""Rep ID"", DIVISION as ""Division"", CITY as ""City"", ADDRESS as ""Address"", RATECODE as ""Ratecode"", METERFORM as ""Meter Form"", METERSTATUS as ""Meter Status"", METERPOINTSTATUS as ""Meter Point Status"", BILLINGCYCLE as ""Billing Cycle"", FILENAME as ""Filename"", FILEDATETIME as ""File Date/Time"" from BAD_METER_LIST"
wherestr = " WHERE"
If MeterID_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " METERID = '" + MeterID_tb.Text + "'"
Else
wherestr = wherestr + " AND METERID = '" + MeterID_tb.Text + "'"
End If
End If
If Division_db.SelectedValue <> "Any" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " DIVISION = " + Division_db.SelectedValue
Else
wherestr = wherestr + " AND DIVISION = " + Division_db.SelectedValue
End If
End If
If DateFrom_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
End If
End If
If DateTo_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
End If
End If
command = New OleDb.OleDbCommand(commandstr + wherestr)
command.Connection = con
con.Open()
oda.SelectCommand = command
oda.Fill(dt)
Me.Grid_Bad_Meters.DataSource = dt
Me.Grid_Bad_Meters.DataBind()
End Sub
#End Region
Protected Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
CleanInput()
RequireFilter()
FillGridView()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Grid_Bad_Meters_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles Grid_Bad_Meters.PageIndexChanging
'Grid_Bad_Meters.Visible = True
Grid_Bad_Meters.PageIndex = e.NewPageIndex
Grid_Bad_Meters.DataBind()
FillGridView()
End Sub
End Class

TreeView expanding wrong node

I have a TreeView in a VB.NET/ASP.NET Application.
The TreeView is being Populated programmatically as the page loads. However, when i try and expand a node it is expanding the wrong node.
Example:I have a node with 5 children. Nodes one and two have children and when i try and expand node two it expands node one and when i try and expand node one it also expands node one.
I have tried re-organizing the structure of the TreeView and Also tried adding the nodes in one by one and still no luck.
Edit:
Below is the Relevant code from my TreeView :
For Each V2MaterialRow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Material Details'", connection)
Dim FormName As String = command.ExecuteScalar()
connection.Close()
V2MaterialNode = New TreeNode
V2MaterialNode.ToolTip = "V2 Material Details"
V2MaterialNode.Text = FormName & " " & V2MaterialRow("Version")
V2MaterialNode.Value = V2MaterialRow("Qno")
V2MaterialNode.ShowCheckBox = True
V2MaterialNode.NavigateUrl = "V2MaterialDetails.aspx?text=" + V2MaterialRow("Qno")
V2MaterialNode.Target = "_blank"
node.ChildNodes.Add(V2MaterialNode)
connection.Open()
command = New SqlCommand("Select * from Specallinone where qno='" + V2MaterialRow("Qno") + "'", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
For Each PurchaseOrderRow In DS.Tables("PurchaseOrder").Rows
PurchaseOrderNode = New TreeNode
PurchaseOrderNode.ToolTip = "Purchase Order"
PurchaseOrderNode.Text = "Purchase Order - " + PurchaseOrderRow("supplier") + " " + PurchaseOrderRow("Ordernumber")
PurchaseOrderNode.Value = PurchaseOrderRow("Qno")
PurchaseOrderNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + PurchaseOrderRow("Qno") + "&Jobno=" + PurchaseOrderRow("JobNumber") + "&Orderno=" + PurchaseOrderRow("Ordernumber") + "&text=" + Replace(PurchaseOrderRow("supplier"), "&", "$") + ""
PurchaseOrderNode.Target = "_blank"
V2MaterialNode.ChildNodes.Add(PurchaseOrderNode)
Next
Else
datareader.Close()
End If
connection.Close()
For Each LabelRow As DataRow In DS.Tables("AllinOne").Rows
Dim Labelnode = New TreeNode
Labelnode.ToolTip = "PO Labels"
Labelnode.Text = "PO Labels"
Labelnode.Value = LabelRow("Qno")
'Labelnode.ShowCheckBox = True
Labelnode.NavigateUrl = "GeneratePOLabels.aspx?text=" + LabelRow("Qno")
Labelnode.Target = "_blank"
Try
connection.Open()
command = New SqlCommand("Select * from purchaseorder where qno='" + LabelRow("Qno") + "' and Jobnumber<>''", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
Exit For
Else
datareader.Close()
V2MaterialNode.ChildNodes.Add(Labelnode)
End If
Catch ex As Exception
Messagebox.Show("Error in Dispalying the Labels...")
Finally
connection.Close()
End Try
Next
Next
For Each MPORow In DS.Tables("ManualPO").Rows
Dim Supplier As String
connection.Open()
command = New SqlCommand("Select Distinct Supplier from ManualPurchaseOrder where ManualDetailsId='" + MPORow("ManualDetailsId").ToString + "' ", connection)
datareader = command.ExecuteReader()
While datareader.Read()
Supplier = Supplier + datareader.Item("Supplier") + ","
End While
datareader.Close()
connection.Close()
MPONode = New TreeNode
MPONode.Value = MPORow("ManualDetailsId")
MPONode.Text = "Manual PO " & MPORow("ManualDetailsId") & " Supplier:" & Supplier.ToString
Supplier = ""
node.ChildNodes.Add(MPONode)
Dim ManualPODetailsDa As New SqlDataAdapter("Select distinct supplier,Jobnumber,ordernumber,Qno from PurchaseOrder where Ordernumber in (Select Distinct OrderNumber From ManualPurchaseOrder where ManualDetailsId = '" + MPORow("ManualDetailsId") + "') ", connection)
Dim ManualPODetailsDs As New DataSet
ManualPODetailsDa.Fill(ManualPODetailsDs)
For Each ManualPODetailsDR As DataRow In ManualPODetailsDs.Tables(0).Rows
MPODNode = New TreeNode
MPODNode.Value = ManualPODetailsDR("OrderNumber")
MPODNode.Text = "Purchase Order - " + ManualPODetailsDR("supplier") + " " + ManualPODetailsDR("Ordernumber")
MPODNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + ManualPODetailsDR("Qno") + "&Jobno=" + ManualPODetailsDR("JobNumber") + "&Orderno=" + ManualPODetailsDR("Ordernumber") + "&text=" + Replace(ManualPODetailsDR("supplier"), "&", "$") + ""
MPODNode.Target = "_blank"
MPONode.ChildNodes.Add(MPODNode)
Next
Next
For Each Takeoffrow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Take-Off-Sheets'", connection)
Dim FormName As String = command.ExecuteScalar()
TakeOffNode = New TreeNode
TakeOffNode.ToolTip = "Take Off Sheets"
TakeOffNode.Text = FormName & " " & Takeoffrow("Version")
TakeOffNode.Value = Takeoffrow("Qno")
TakeOffNode.ShowCheckBox = True
TakeOffNode.NavigateUrl = "TakeOffSheet.aspx?text=" + Takeoffrow("Qno")
TakeOffNode.Target = "_blank"
node.ChildNodes.Add(TakeOffNode)
command = New SqlCommand("Select count(*) from ManualTakeOffSheet where srecid in (Select Distinct Srecid from Specdetails where Quoteno='" + Takeoffrow("Qno") + "')", connection)
Dim MTS As Integer = 0
MTS = command.ExecuteScalar()
connection.Close()
If MTS > 0 Then
Dim ManualTakeoffnode As New TreeNode
ManualTakeoffnode.ToolTip = "Manual Take Off Sheets"
ManualTakeoffnode.Text = "Manual Take Off Sheets" & " " & Takeoffrow("Version")
ManualTakeoffnode.Value = Takeoffrow("Qno")
ManualTakeoffnode.NavigateUrl = "ManualTakeOffSheet.aspx?text=" + Takeoffrow("Qno")
ManualTakeoffnode.Target = "_blank"
TakeOffNode.ChildNodes.Add(ManualTakeoffnode)
End If
Next
Sometimes if you have a node which shares the same value as another node - unexpected behavior can occur (one node opening when the other is clicked)
Node values must be unique
Debug your code and ensure that all your nodes have a unique value.
The value will be stored in node.Value
In your case, the node.Value is populated from a table.
Ensure that TakeOffNode.Value = Takeoffrow("Qno") does not equal MPODNode.Value = ManualPODetailsDR("OrderNumber")

SQL statement in for loop only updating once

if request.form("submitChange") = "site" then
for i = 0 to UBound(arrmode)
SQLstr = "UPDATE SCSer SET Ser_Site_Num = '" & request.form("site_to") & "' WHERE Ser_Num = '" & arrmode(i) & "'"
conn.execute(SQLstr)
Response.Write("SUCCESSFULLY UPDATED! " + arrmode(i))
next
end if

advanced search page for web application using vb.net

i created a simple advanced search page for web application, i thought sharing it with you might help beginners
the following is an example of an advanced search page for an employee database using VB.Net
the following is the code behind page
Imports System.Data.OleDb
Partial Class searchme
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mydb As New OleDbConnection
mydb = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|employee.mdb;Persist Security Info=True")
mydb.Open()
Dim sqlstring = "select * from [dataview] where "
If MRNTextBox1.Text <> "" Then sqlstring = sqlstring + "[code] like '%" + CodeNameTextBox1.Text + "%' OR [EmployeeName] like '%" + CodeNameTextBox1.Text + "%' AND "
If GOVDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Governorate] ='" + GOVDDL.SelectedItem.Text + "' AND "
If genderddl.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Gender] ='" + genderddl.SelectedItem.Text + "' AND "
If DateEmploymentFrom.Text <> "" And DateEmploymentTo.Text <> "" Then sqlstring = sqlstring + "[DateEmployment] >= #" + DatumKonvert1.DK1(DateEmploymentFrom.Text) + "# AND [Datepresentation] <= #" + DatumKonvert1.DK1(DateEmploymentTo.Text) + "# AND "
If DepartmentDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Department] ='" + DepartmentDDL.SelectedItem.Text + "' AND "
sqlstring = Left(sqlstring, Len(sqlstring) - 5) + " order by " + OrderByDDL.SelectedItem.Text
Dim myds As New AccessDataSource
myds.DataFile = "~\App_Data\employee.mdb"
myds.SelectCommand = sqlstring
' Dim Mygrid As New GridView
Mygrid.DataSource = myds
Mygrid.DataBind()
' Me.form1.Controls.Add(Mygrid)
mydb.Close()
RecCount.Text = "Filtered Record Count = " + mygrid.Rows.Count.ToString
Session("dsource") = myds
Response.Redirect("sresults.aspx")
End Sub
End Class
you did a good job, also try the following
link text
link text

Resources