i have a project, and part of it asks the user to input the ID of the patient to show his/her details
This is my code
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
if (dbReader.HasRows)
{
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
}
}
}
}
in the IF statement, i dont know what to write in it, to display on the row of the patient with this ID only
Please Help!!
Instead of selecting all rows, it is much more efficient to filter the one row you are looking for using a parameter and modifying your SQL statement as follows.
sql = "SELECT * FROM Patients WHERE PatientID = [pID]";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("pID", 101);
dbReader = dbCmd.ExecuteReader();
I would also suggest looking into the "using" clause. Here's a SO example.
sql = "SELECT Count(*) FROM Patients WHERE PatientID = #PID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("#PID", 101);
Int32 Cnt = dbCmd.ExecuteScalar();
if ( Cnt > 0)
{
// Do Something
}
else { // Do something}
you have to use a variable to be sure that your ID was found and and break; to exit your loop once it was found
if (dbReader.HasRows)
{
bool found = false;
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
found = true ; Break;
}
}
}
}
int anInteger = Convert.ToInt32(textBox7.Text);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients where PatientID=#PatientID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Parameters.AddWithValue("#PatientID",anInteger);
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
while (dbReader.Read())
{
//now display the reader values here : sample
//TextBox1.Text=dbReader["name"].ToString();
}
Related
I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}
public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.
They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.
I am trying to display pictures from my SQLSEVER database on my website. My users have a picture field with a picture datatype. If the picture column is null, then I want the picture displayed to be a egg.jpg, but right now for every person their picture is egg.jpg, even if they have a picture in the database. Here is my method.
public string getImageUrl()
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection();
sc.ConnectionString = "Server =MRCOMPUTER2\\SQLEXPRESS; Database = WBL;Trusted_Connection=Yes;";
sc.Open();
System.Data.SqlClient.SqlCommand insert = new System.Data.SqlClient.SqlCommand();
insert.Connection = sc;
insert.CommandText = "SELECT profilePicture from SystemUser";
insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();
string url = "";
while (reader.Read())
{
if ( !DBNull.Value.Equals(reader[0]))
{
url = "data:Image / png; base64," + Convert.ToBase64String((byte[])reader[0]);
}
else {
url = "images/egg.jpg";
}
}
return url;
}
Your code returns the image for the last user in your table.
Here:
insert.CommandText = "SELECT profilePicture from SystemUser";
you select all users from the table (not just the one you currently show). Then:
while (reader.Read())
{
...
url = ...
...
}
you re-assign url inside every iteration of your while loop. This is semantically equivalent to:
url = ... /* The value determined from the last record of the reader. */
Thus, all your users show the same image - the one of the last user in your table.
You SELECT statement is attached into a ExecuteNonQuery?
Take it off.
Just perform the READER statement...
Try this:
static void Main(string[] args)
{
string connectionString = "Server=.;Database=AA;Trusted_Connection=True;";
/*
CREATE TABLE [dbo].[SystemUser]
(
[ProfilePicture] [varbinary](max) NULL
)
*/
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (#ProfilePicture);
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (NULL);
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
byte[] bytes = File.ReadAllBytes(#"1.jpg");
command.Parameters.AddWithValue("#ProfilePicture", bytes);
connection.Open();
command.ExecuteNonQuery();
}
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
SELECT TOP 1000 [ProfilePicture] FROM [AA].[dbo].[SystemUser];
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
}
var rows = ds.Tables[0].Rows.Cast<DataRow>();
foreach (DataRow row in rows)
{
byte[] bytes = row.Field<byte[]>(0);
if (bytes != null)
{
string fileName = Guid.NewGuid().ToString("N") + ".jpg";
File.WriteAllBytes(fileName, bytes);
}
}
}
Can you try using the name of the column such as
var Val = (String)reader["column name"];
Also, try something like this to test:
while (reader.Read())
{
var testVal = reader.GetString(0);
Var testVal2 = reader.GetString(1);
today, I am trying to use DataRoutines to insert some values into my Access Database. However, it did not work as well as there were no records created. Does anyone know what's wrong with my code?
This is my DataRoutines (dataroutines2) file
public void CreateRecs(string strUserId)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
OleDbCommand cmd; OleDbDataReader rdr;
string strSql;
string strOFlag = "F";
// check to see if there is an active order record
strSql = "SELECT eStatus FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
Boolean booRows = rdr.HasRows;
if (booRows) //when booRows is true, there are order records for the user
{
rdr.Read();
if ((string)rdr["eStatus"] != "Ordering") //status of an active order is "Ordering"
{
strOFlag = "M"; //"T" means there is a need to create a new Orders record
}
else { strOFlag = "M"; }
mDB.Close();
if (strOFlag == "M")
{
//insert a new order record
string strStatus = "Ordering";
strSql = "INSERT INTO enrolInfo (eUserId, eStatus) VALUES (#UserId, #Status)";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.AddWithValue("#UserId", strUserId);
cmd.Parameters.AddWithValue("#Status", strStatus);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
}
//get back order No - this order no is needed when the user buys an item
strSql = "SELECT eEnrolNo FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
Session["tOrderNo"] = rdr["eEnrolNo"]; //store the active order no in the sOrderNo
mDB.Close();
return;
}
}
This is the code that will route the solution to the DataRoutines file in my Register Page
//prepare Session variables for newly register customer
Session["sFlag"] = "M";
Session["tUserId"] = (string)txtUserId.Text;
Session["tName"] = (string)txtName.Text;
Session["tAddress"] = (string)txtAddress.Text;
Session["tTel"] = (string)txtTel.Text;
Session["tEmail"] = (string)txtEmail.Text;
String strUserId = (string)Session["tUserId"];
DataRoutines2 DRObject = new DataRoutines2();
DRObject.CreateRecs(strUserId);
Thanks for your help