Auto Suggestion textbox - sql-server

I want to have a auto suggestion textbox which will show the name of employee after typing a specific letter. The name is present in the employee table in three columns i.e firstname, middlename, lastname.
I have tried a code for this but it can show only one column of the table i.e the firstname.
How to concatenate all the three columns so that they are suggested in the textbox.
My code:
Dim strSql As String = "select P_Firstname, P_MiddleName, P_LastName from Patient_Registration"
Dim dtb As New DataTable
Using cnn As New SqlConnection(conn)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
txtsearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtsearch.AutoCompleteSource = AutoCompleteSource.CustomSource
If dtb.Rows.Count > 0 Then
Dim i As Integer = 0
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName"))
Next
End If

Use:
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName") &
dtb.Rows(i)("P_MiddleName") &
dtb.Rows(i)("P_LastName"))
Next
Instead of:
For i = 0 To (dtb.Rows.Count - 1)
txtsearch.AutoCompleteCustomSource.Add(dtb.Rows(i)("P_FirstName"))
Next

<asp:TextBox ID="ddlcenter" runat="server" Font-Size="10px" TabIndex="1" Width="150px"
Style="text-transform: capitalize;"
placeholder="Type Center Name/Code" autocomplete="off"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCenter" MinimumPrefixLength="2" CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10" TargetControlID="ddlcenter" UseContextKey="true"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false" CompletionListCssClass="completionList"
CompletionListHighlightedItemCssClass="itemHighlighted" CompletionListItemCssClass="listItem">
</cc1:AutoCompleteExtender>

[enter image description here][1]
[1]: https://i.stack.imgur.com/g6TR9.png
Showing above result.
enter code here
My code is :
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCenter(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
string cmdText = "Select centername from Center_Master WHere Active=1 and centername like '%' +#SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmdText += " order by centername ";
cmd.CommandText = cmdText;
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["centername"].ToString());
}
}
conn.Close();
return customers;
}
}
}

Related

How can i check if the user entered correct user name and password in DBA_USERS?

So i have a function for when clicking the button, the application would get the username and password stored in a table in oracle, and then compare it to the values entered in the textbox.
My question is that, instead of getting the values from the pre-created table, can i get the values from the DBA_USERS table, since the password is hashed?
Here's the code that fetch data from a created table:
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=localhost:1522/ORCL;DBA Privilege=SYSDBA;User Id=sys;Password=123456;";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
OracleCommand cmd1 = new OracleCommand();
OracleParameter parm = new OracleParameter();
OracleParameter parm1 = new OracleParameter();
parm.OracleDbType = OracleDbType.Int64;
cmd.Connection = conn;
cmd.CommandText = "Select * from Users";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
if (textBox1.Text.Equals(dr["username"].ToString()) && textBox2.Text.Equals(dr["password"].ToString()))
{
MessageBox.Show("Successful", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
var menu = new Menu();
menu.Show();
this.Hide();
}
}
}

Login for users of different positions

I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.

Creating Crystal Report dynamically

I want to create a Crystal Report at runtime by selecting the fields for the report from the treeview. The treeview consists of table names and the column names as the child node. After selecting the column names from the treeview, a "Generate Report" button has to be clicked, which will display the Crystal Report of the selected fields. How can I do this?
Public Class Form1
Dim objRpt As CrystalReport1
Dim con As New SqlConnection
Private Function CreateSelectQueryAndParameters() As String
Dim reportDocument As New ReportDocument
Dim paramFields As New ParameterFields
Dim paramField As ParameterField
Dim paramDiscreteValue As ParameterDiscreteValue
Dim query As String = "SELECT "
Dim columnNo As Integer = 0
If CheckBox1.Checked Then
columnNo = columnNo + 1
query = query.Insert(query.Length, "pcode as Column" + columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Code"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
If CheckBox2.Checked Then
columnNo = columnNo + 1
If (query.Contains("Column")) Then
query = query.Insert(query.Length, ", ")
End If
query = query.Insert(query.Length, "pname as Column" +
columnNo.ToString())
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = "Property Name"
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
End If
For i As Integer = columnNo To 2
columnNo = columnNo + 1
paramField = New ParameterField()
paramField.Name = "col" + columnNo.ToString()
paramDiscreteValue = New ParameterDiscreteValue()
paramDiscreteValue.Value = ""
paramField.CurrentValues.Add(paramDiscreteValue)
paramFields.Add(paramField)
Next
CrystalReportViewer1.ParameterFieldInfo = paramFields
query += " FROM propdb"
Return query
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
objRpt = New CrystalReport1()
con.ConnectionString = "Data Source=MY-PC; Initial Catalog=hrmdb; Integrated Security=True"
con.Open()
Dim query As String = CreateSelectQueryAndParameters()
If Not query.Contains("Column") Then
MessageBox.Show("No selection to display!")
Return
End If
Try
**' I DON'T KNOW WHAT CODE TO ADD HERE'**
CrystalReportViewer1.ReportSource = objRpt
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
End Class
I had a similar program in C#, but they used Access in it and I am using SQL Server now:
public partial class Form1 : Form
{
CrystalReport1 objRpt;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
objRpt = new CrystalReport1();
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\db1.mdb";
//Get Select query Strring and add parameters to the
//Crystal report.
string query = CreateSelectQueryAndParameters();
//if there is no item select,then exit from the method.
if (!query.Contains("Column"))
{
MessageBox.Show("No selection to display!");
return;
}
try
{
OleDbConnection Conn = new OleDbConnection(connString);
OleDbDataAdapter adepter = new OleDbDataAdapter(query, connString);
DataSet1 Ds = new DataSet1();
adepter.Fill(Ds, "Customer");
objRpt.SetDataSource(Ds);
crystalReportViewer1.ReportSource = objRpt;
}
catch (OleDbException oleEx)
{
MessageBox.Show(oleEx.Message);
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
/// <summary>
/// This method is used to
/// 1. create SELECT query according to the selected column names and
/// 2. create parameters and assign values for that parameter that correspond to
/// the crystal report.
/// NOTE: This parameter is used to display column names of the Crystal Report
/// according to the user selection.
/// </summary>
/// <returns></returns>
private string CreateSelectQueryAndParameters()
{
ReportDocument reportDocument;
ParameterFields paramFields;
ParameterField paramField;
ParameterDiscreteValue paramDiscreteValue;
reportDocument = new ReportDocument();
paramFields = new ParameterFields();
string query = "SELECT ";
int columnNo = 0;
if (chbCode.Checked)
{
columnNo++;
query = query.Insert(query.Length, "Code as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Customer Code";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbFirstName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "FirstName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "First Name";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbLastName.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "LastName as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Last Name";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbAddress.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Address as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Address";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
if (chbPhone.Checked)
{
columnNo++;
if (query.Contains("Column"))
{
query = query.Insert(query.Length, ", ");
}
query = query.Insert(query.Length, "Phone as Column" + columnNo.ToString());
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "Phone";
paramField.CurrentValues.Add(paramDiscreteValue);
// Add the paramField to paramFields
paramFields.Add(paramField);
}
//if there is any remaining parameter, assign empty value for that
//parameter.
for (int i = columnNo; i < 5; i++)
{
columnNo++;
paramField = new ParameterField();
paramField.Name = "col" + columnNo.ToString();
paramDiscreteValue = new ParameterDiscreteValue();
paramDiscreteValue.Value = "";
paramField.CurrentValues.Add(paramDiscreteValue);
//Add the paramField to paramFields
paramFields.Add(paramField);
}
crystalReportViewer1.ParameterFieldInfo = paramFields;
query += " FROM Customer" ;
return query;
}
}

ComboBox Shows System.Data.DataRow (MVC)

My Combobox does not show me the values in my SQL-Attribute "TimeBlock", instead it shows System.Data.DataRow 5 Times. What is wrong with my code?
Code:
//DAL:
public class DAL{
string ConnectionString = "server=ICSSQL13\\Grupp28,1528; Trusted_Connection=yes; database=Yoloswag";
public DataTable StoreSqlDataInComboBoxTP()
{
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();
string StoreSqlDataInComboBoxTP = "SELECT TimeBlock FROM TimePeriod GROUP BY TimeBlock";
SqlCommand Cmd = new SqlCommand(StoreSqlDataInComboBoxTP, Conn);
SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
DataSet DSet = new DataSet();
Adapter.Fill(DSet);
Adapter.Dispose();
Cmd.Dispose();
Conn.Close();
Conn.Close();
return DSet.Tables[0];
}
}
//Controller:
public class Controller
{
DAL Dal = new DAL();
public DataTable storesqldataincomboboxtp()
{
return Dal.StoreSqlDataInComboBoxTP();
}
}
//View:
public partial class Booking : Form
{
Controller controller = new Controller();
DataTable DTable = new DataTable();
DataSet DSet = new DataSet();
//Ignore string UserName
public Booking(string UserName){
DTable = controller.storesqldataincomboboxtp();
if (DTable.Rows.Count > 0)
{
for (int i = 0; i < DTable.Rows.Count; i++)
{
CBTime.Items.Add(DTable.Rows[i].ToString());
}
}
}
}
Instead of the 5 System.Data.DataRow I want to show what is stored in "TimeBlock".
"SELECT TimeBlock From TimePeriod GROUP BY TimeBlock" shows:
"08-00 - 10:00"
"10:00 - 12:00"
"12:00 - 14:00"
"14:00 - 16:00"
"16:00 - 18:00"
How can i solve this?
Thanks
You are not getting to the Field level when you are calling the Add() on CBTime. Something like this within your conditional checking that your table has rows would work:
foreach (DataRow dRow in DTable.Rows)
{
CBTime.Items.Add(dRow["TimeBlock"]);
}

Can't read an image from database

I'm trying to read an image from a SQL Server database, but I'm get an error:
Parameter is not valid
Who can help me? How to fix it?
byte[] im = connection.ReadImg(id);
if (im != null)
{
MemoryStream st1 = new MemoryStream(im);
pictureBox1.Image = Image.FromStream(st1);
}
else
pictureBox1.Image = Image.FromFile(fn);
public byte[] ReadImg(string id)
{
cmd.Connection = con;
cmd.CommandText = "SELECT photo FROM User WHERE id=" + id;
byte[] image = null;
con.Open();
try
{
image = (byte[])cmd.ExecuteScalar();
}
catch
{
image = null;
}
con.Close();
return image;
}
If id is a string, you have to pass it as a string:
cmd.CommandText = "SELECT photo FROM User WHERE id=#id";
cmd.Parameters.AddWithValue("#id", id);
If not using the recommended parameter way, the problem is you need to have the string parameter enclosed in single quotes:
cmd.CommandText = "SELECT photo FROM User WHERE id='" + id + "'";
This is considered bad practice.
The SELECT statement does not return a scalar; you need to use ExecuteReader or similar;
SqlDataReader reader = cmd.ExecuteReader();
using(reader)
{
while(reader.Read())
{
// Do something with reader["photo"].
}
}
To provide more we need the data types of id and photo.

Resources