Using Image Stored in Database (image path) - c#

I want this button's image use the image stored in database (image path)...
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = ("Select link from testtable where ID=" + a);
try
{
conn.Open();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button11.Image = reader["path"].ToString();
}
}
I think the error lies in "reader["path"].ToString();" but I don't know what syntax to use.

If you stored the path to the image file on the disk in the path column, you should laod the image:
string path = (string)reader["path"];
button11.Image = Image.FromFile(path);
Side note: Never pass the values directly from a user input to a database query. It is vulnerable to sql injection attacks. Use parameters instead:
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));

try this:
while (reader.Read())
{
string path = reader.GetString(0);
button11.Image = Image.FromFile(path);
}

Try this: ( Written right to answer box, may be there are typo! )
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string imagePath;
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand command = conn.CreateCommand())
{
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));
try
{
conn.Open();
imagePath= (string)command.ExecuteScalar();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
button11.Image = Image.FromFile(imagePath);
}
}

Related

Output Not Displaying in TextBox in C#

I am new to C# and I have connected it with Oracle11g and using Visual Studio 2013 as a tool. I am trying to display a 'name ' that is being returned by a query to a textbox but it is neither displaying an Error Message nor displaying the Output. Pleases help me to resolve this problem. Thanks... here is my code..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
after setting textBox1.Text = dr.GetString(0);
it is giving me the attached exception.
Array indexes start at index zero, not 1. The returned string (if any) is at
textBox1.Text = dr.GetString(0);
A more correct way to write your code is the following
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
And if your code is supposed to return just a single record with a single column then you can use the more performant ExecuteScalar without building an OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();

SqliteDataReader doesn't work in C#?

I have some data stored in a SQLite database which I want to display on a webpage in C#. I searched for the right thing to do but only found console.writeline, and beside that the SqliteDataReader function is not working. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
command.Connection = conn;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
string test = ("Name: " + reader["name"] + "\tScore: " + reader["score"]);
command.ExecuteNonQuery();
conn.Close();
}
}
What should I do?
Thanks in advance,
Elias
It seems that you've forgot to put the actual query to perform:
command.CommandText = "...";
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
//TODO: do not hardcode connection string, move it to settings
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
// var for simplicity
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
//TODO: put the right SQL to perform here
command.CommandText =
#"select name,
score
from MyTable";
using (var reader = command.ExecuteReader()) {
string test = "";
// do we have any data to read?
//DONE: try not building string but using formatting (or string interpolation)
if (reader.Read())
test = $"Name: {reader["name"]}\tScore: {reader["score"]}";
//TODO: so you've got "test" string; do what you want with it
}
}
//DONE: you don't want command.ExecuteNonQuery(), but command.ExecuteReader()
//DONE: you don't want conn.Close() - "using" will do it for you
}
}

How to save an image database and display it on a panel on webpage?

I created a folder on a webform in visual studio for images and titled as (Invoices), I want to save the root of images in MySql database and display the images on a panel one the webpage. The image has been saved on the folder but not on database.
The Codes I have tried
protected void Page_Load(object sender, EventArgs e)
{
string connection = "server=localhost; userid= ; password= ; database=admindb; allowuservariables=True";
MySqlConnection cn = new MySqlConnection(connection);
try
{
string sqlcmd = "SELECT PicAddress FROM InvoicesFP WHERE InvoicesFP_ID=#InvoicesFP_ID";
cn.Open();
MySqlCommand cmd = new MySqlCommand(sqlcmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string url = rdr["PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch (Exception ex)
{
throw ex;
}
cn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + FileExtension;
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into invoicesfp (PicAddress), VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", Server.MapPath("~/Invoices"));
cmd.Connection.Open();
cmd.BeginExecuteNonQuery();
cmd.Connection.Close();
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
}
#endregion
}
Update
Try this Code first, using this sample you do not need to use Rename Method And whatever its Extension is, it is supported:
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + "." + FileExtension;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
#endregion
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO InvoicesFP (PicAddress) VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", "PicAddress");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
then in your page_load you can call the Select Query to get the Address out database and pass it over to control e.g:
const string DB_CONN_STR = "Server=etc;Uid=etc;Pwd=etc;Database=etc;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try {
string sqlCmd = "SELECT PicAddress FROM [YourTable] where Id == PicAddress id";
cn.Open(); // have to explicitly open connection (fetches from pool)
MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string url = rdr["Name of the Field Assuming PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch(Exception ex)
{
throw ex;
}
Thats All - Happy Coding

Why I get Syntax error in INSERT INTO statement?

protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
OleDbConnection con = new OleDbConnection(strConnString);
string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(#FN, #FP, #AN)";
OleDbCommand cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#FN", FileName);
cmd.Parameters.AddWithValue("#FP", "images/" + FileName);
cmd.Parameters.AddWithValue("#AN", txtAlbumname.Text.ToString());
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string var = DropDownList1.SelectedItem.ToString();
txtAlbumname.Text = var.ToString();
}
}
I Have tried almost everything , but this error keeps on coming.
I have put on the brackets aswell incase of reserved words but still this error is showing
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
For Example
OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText =
"SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);
for (int j=0; j<parameters.Length; j++)
{
command.Parameters.Add(parameters[j]) ;
}
for reference ..
MSDN
IMAGE is a reserved word in Access SQL so to use it as a table name you must also enclose it in square brackets:
string strQuery = "INSERT INTO [image] ([FileName], ...

check existing record before inserting sql database

I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..
code:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Val1", txtName.Text);
cmd.Parameters.AddWithValue("#Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("#Val2", txtDept.Text);
cmd.Parameters.AddWithValue("#Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("#Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("#training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
this way , your query will insert data only if not exists already
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id and not exists (select 1 from personTraining pp where pp .employeeid=#Val4) ";

Categories