Inserting picture from picturebox into database - c#

namespace dota2
{
public partial class Form1 : Form
{
private SqlConnection cn = new SqlConnection();
private SqlCommand cmd = new SqlCommand();
private SqlDataReader dr;
private SqlParameter picture;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::dota2.Properties.Settings.Default.Database1ConnectionString);
cmd.Connection = cn;
picture = new SqlParameter("#picture", SqlDbType.Image);
}
private void button1_Click(object sender, EventArgs e)
{
open();
}
private void button2_Click(object sender, EventArgs e)
{
savepicture();
}
private void savepicture()
{
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#picture", a);
cmd.CommandText = "insert into pictures (name,picture) values ('" + textBox1.Text.ToString() + "',#picture)";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
textBox1.Text = "";
pictureBox1.Image = null;
MessageBox.Show("Image Saved", "Programming At Kstark");
}
}
private void open()
{
try
{
OpenFileDialog f = new OpenFileDialog();
f.InitialDirectory = "C:/Picture/";
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 0;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(f.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BorderStyle = BorderStyle.Fixed3D;
textBox1.Text = f.SafeFileName.ToString();
}
}
catch { }
}
}
}
My form has a picturebox and Open and Save buttons. I'm trying to insert the picture from my picturebox into database using the code below. Picture opens as it should and shows up in the picturebox, but pressing the save button isn't working. It says either cn. Open is an error or the executenonquery.

Related

What should I do if I want the value of the dgv1(datagridview) to be shown on a different form?

Form1
namespace erpmam
{
public partial class Form1 : Form
{
MySqlDB mySqlDB;
SqlDataAdapter adpt;
DataTable dt;
SqlConnection con;
public void showdata()
{
adpt = new SqlDataAdapter("select deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms from sys_department;",con);
dt = new DataTable();
adpt.Fill(dt);
dgv1.DataSource = dt;
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
mySqlDB = new MySqlDB("server=······");
}
private SqlDataAdapter MySqlDataAdapter(string v, MySqlConnection con)
{
throw new NotImplementedException();
}
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void BTN_INSERT_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_id like '%" + textBox1.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_name like '%" + textBox2.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form3 Form3 = new Form3();
Form3.ShowDialog();
}
}
}
Form2
namespace erpmam
{
public partial class Form2 : Form
{
MySqlConnection connection = new MySqlConnection("datasource =······");
MySqlCommand command;
public Form2()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO sys_department(DEPTMT_ID, DEPTMT_NAME, DEPTMT_SEQ, REG_YMDTMS) VALUES(" + textBox1.Text + ',' + textBox2.Text + ','+ textBox3.Text + ','+ "NOW()" +")";
connection.Open();
MySqlCommand command = new MySqlCommand(insertQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Form3
namespace erpmam
{
public partial class Form3 : Form
{
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; Initial Catalog = 'erp'; username = root; password=610822");
MySqlCommand command;
public Form3()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
} public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
string updateQuery = " UPDATE sys_department";
updateQuery += " SET DEPTMT_NAME = '" + textBox2.Text + "', DEPTMT_SEQ = '" + textBox3.Text + "', mod_ymdtms = NOW()";
updateQuery += " where DEPTMT_ID = '" + textBox1.Text + "'";
connection.Open();
MySqlCommand command = new MySqlCommand(updateQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("changed normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_delete_Click(object sender, EventArgs e)
{
string deleteQuery = " DELETE from sys_department";
deleteQuery += " where DEPTMT_ID = '" + textBox1.Text + "' or DEPTMT_NAME = '" + textBox2.Text + "' or DEPTMT_SEQ = '" + textBox3.Text + "'" ;
connection.Open();
MySqlCommand command = new MySqlCommand(deleteQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Simply you can create a Global variable of Datatable to use it as source of Data and you can use it anywhere in your Forms
This is the GLobal Class
//make sure to import this System.Data
using System.Data;
class Global
{
private static DataTable source;
public static DataTable Source
{
get
{
// Reads are usually simple
return source;
}
set
{
// You can add logic here for race conditions,
// or other measurements
source = value;
}
}
}
In your first form
string connectString = "datasource=xxxx;port=3306;username=xxxx;password=;database=xxxxx;";
MySqlConnection conn;
MySqlCommand comm;
MySqlDataReader read;
MySqlDataAdapter adapter;
Global mySource;
void getData() {
string query = "Select * from tableName";
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
adapter = new MySqlDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
//setting up
Global.Source = ds.Tables[0];
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
In you second Form
public Form2()
{
InitializeComponent();
dataGridView1.DataSource = Global.Source;
}
Simply you can create static method in the class of form3 and accept one argument from DataGridView type and call this method from form1 and pass dg1 after filling it with rows then you can access it now from this static method...
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e) {
Form3 Form3 = new Form3();
Form3.staticMethodToPassDGVBetweenTwoForms(dgv1);
Form3.ShowDialog();
}
namespace erpmam {
public partial class Form3 : Form {
public Form3() {
initializeComponent();
}
public static void staticMethodToPassDGVBetweenTwoForms(DataGridView dgv1){
//do anything with dg1 now
}
}

How to do a searching through database from a keyword inputted from textbox? in c#

I have a program which user can input some data and the data will be storaged into a database (i use Ms Access). But, the program also can do some search of existing data from database. User can input a keyword from textbox and the program will show the data from database.
Like this:
User will input a keyword or a text to "Kd. Dosen" textbox then it will show the data from database contains that keyword. Here is the database:
Can anybody help me how to do this?
Anyway, here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//stri
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryInsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP)values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryInsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dimasukkan!");
}
catch
{
MessageBox.Show("Gagal memasukkan data");
}
finally
{
vconnect.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "update MstDosen set NaDosen = #namadosen, Alamat = #alamat, NoTelp = #notelp, NoHP = #nohp where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil diubah!");
}
catch
{
MessageBox.Show("Gagal mengubah data");
}
finally
{
vconnect.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "delete from MstDosen where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
//vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
//vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
//vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
//vinsert.Parameters.AddWithValue("#nohp", textBox2.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dihapus!");
}
catch
{
MessageBox.Show("Gagal menghapus data");
}
finally
{
vconnect.Close();
}
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
DataList dat = new DataList();
dat.Show();
}
public void insert()
{
if(textBox1.Text != "" && textBox2.Text != "")
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryinsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP) values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryinsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
}
else
{
MessageBox.Show("Data Belum Dimasukkan");
}
}
}
You have to add textbook_change option to double click textbook which you want to write text and filter.
private void txtCariKodu_TextChanged(object sender, EventArgs e)
{
FilterByName();
}
your method is contains a variable which is your db query like (SELECT * FROM YOUTRABLE WHERE NAME LIKE % ).
and now you can show filtered values on your Datagridview.
public void FilterByName()
{
var result = YOURSQLQUERY.ToList();
dataGridView1.DataSource = result;
}

Update SQL query, unsure why it isn't working as no errors are appearing

I have been staring at this UPDATE statement for a long while and are unsure why my table isn't changing. When I press the button no error appears but my table doesn't not get updated either, I have checked that all of my variables have values on debug and they do.
I'd appreciate any help anyone can give me!
This is the code that contains the statement I need help with:
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
This is the whole code for my form if anyone wanted to look at it just in case that is affecting the button even handler:
namespace ComputingA2_Official_Project
{
public partial class CurrentlySetTestForm : Form
{
Timer loopTimer = new Timer();
private int CurrentQuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) AS QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=#Signedinstudent AND [StudentAnswer] IS NULL )", connect);
command18.Parameters.AddWithValue("#Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
CurrentQuestionID = Convert.ToInt32(reader[0]);
SqlCommand command19 = new SqlCommand("SELECT ([Question Space]) FROM Questions WHERE ([QuestionID]=#CurrentQID)", connect);
command19.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
using (SqlDataReader reader2 = command19.ExecuteReader())
{
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2[0]);
label1.Text = QuestionSpace;
}
}
}
connect.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
I believe the issue is that you are executing the command asynchronously (BeginExecuteNonQuery), but never calling EndExecuteNonQuery to commit it. I also suspect you could just call it synchronously like this:
command20.ExecuteNonQuery();

Getting a picture from MS Access in to a picturebox in C#

Hi I have used the code below to save images to my database,
but now I want to know how I can get the picture from the database to a PictureBox
can you please help me.
private void button1_Click(object sender, EventArgs e)
{
ofdFoto.ShowDialog();
string i = ofdFoto.FileName.ToString();
pbxFoto.ImageLocation = i;
}
private void button2_Click(object sender, EventArgs e)
{
dbConn.Open();
string querys = "INSERT INTO Fruits (Name, Picture) VALUES ('" + txtName.Text + "','" + ImageToByte(pbxFoto.Image) + "')";
OleDbCommand cd = new OleDbCommand(querys, dbConn);
cd.ExecuteNonQuery();
dbConn.Close();
MessageBox.Show("Picture saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
private void button1_Click(object sender, EventArgs e)
{
PictureBox p =new PictureBox();
p.ImageLocation = ofdFoto.FileName.ToString();
p.Location = new Point(100, 100);
this.Controls.Add(p);
}
See if this helps you!!
Try this code:
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
var img = (Bitmap)Image.FromStream(ms);
return img;
}
}
and set to PictureBox.Image property:
pictureBox1.Image = BytesToBitmap(byteArray);

FileUpload in FormView

I have a problem regarding with add an image URL within a database.I'm using fileupload method within formview in ASP.Net.And I have a table called duyurular
which can be record a image URL.BTW,I'm using SQL Server Database.
My question is;I'm doing the process update,delete and to make an announcement in the FormView.I can upload those images within folder called "img" with FileUpload.
However,I want to record it within database as well.when to add within database another those infos,there are no the image URL.
Finally,I can't add the image URL within database.
Here is my code;
public partial class panel_yoneticipaneli : System.Web.UI.Page
{
FileUpload dosya, dosya1;
//TextBox t1, t2, t3;
//Button btn;
SqlConnection con;
static string str = "Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True";
string yol = "";
protected void Page_Load(object sender, EventArgs e)
{
dosya = (FileUpload)FormView2.FindControl("FileUpload1");
dosya1 = (FileUpload)FormView2.FindControl("FileUpload2");
// btn = (Button)FormView2.FindControl("ResimKaydetButonu");
//t1 = (TextBox)FormView2.FindControl("DuyuruBaslikTextBox");
//t2 = (TextBox)FormView2.FindControl("DuyuruIcerikTextBox");
//t3 = (TextBox)FormView2.FindControl("DuyuruTarihiTextBox");
Label1.Visible = false;
if (Session["KullaniciID"]!=null)
{
con = new SqlConnection(str);
SqlCommand sorgu = new SqlCommand("SELECT * FROM Kullanici WHERE KullaniciAdi=#KullaniciAdi", con);
sorgu.Parameters.Add("#KullaniciAdi", SqlDbType.VarChar).Value = Session["KullaniciAdi"];
con.Open();
SqlDataReader oku = sorgu.ExecuteReader(CommandBehavior.CloseConnection);
Label1.Visible = true;
while (oku.Read())
{
Label1.Text = oku["KullaniciAdi"].ToString();
}
}
else {
Response.Redirect("error.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
Response.Redirect("giris.aspx");
}
protected void btn_Click(object sender,EventArgs e) {
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
System.Drawing.Image resim = System.Drawing.Image.FromFile(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
resim.Dispose();
DbUpload();
}
}
catch (Exception ex)
{
}
}
public void DbUpload() {
try {
SqlConnection sc = new SqlConnection("Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True");
SqlCommand scom = new SqlCommand("insert into Duyuru(DuyuruResmi) values(#DuyuruResmi)", sc);
scom.Parameters.AddWithValue("#DuyuruResmi", dosya.FileName);
scom.ExecuteNonQuery();
sc.Close();
}catch(Exception p){
p.Message.ToString();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
Response.Write("Fileupload çalışıyor...");
DbUpload();
}
}
catch (Exception ex)
{
}
}
thanks in advance for all comments you can share.
I suggest that you just upload the image name without specifying the full URL, and you can save the image base path in the web.config like '<add key="ImagesBasePath" value="/img" />' so you can change the path were you have your images and you can control the view of this image by concatenating the Image name to ConfigurationManager.AppSettings["ImagesBasePath"] so this will be better.
You have to use Formview ItemInserting Event, where you can pass in the built URL.
protected void frmAsset_ItemInserting(object sender, FormViewInsertEventArgs e)
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
e.NewValues["URL"] = "img/" + dosya.FileName;
}
}

Categories