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;
}
}
Related
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;
}
Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button
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.
i using a single master page in asp.net for log-In and Log-Out functionality...
but in master page session name takes null value.
Here is my code ,please help me...
MasterPage.master.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["name"] == null)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
else if (Session["name"] != null)
{
Panel1.Visible = false;
Panel2.Visible = true;
Label2.Text = "WELCOME | Mr." + Session["name"].ToString();
}
}
}
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
}
my homepage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string st="select Label4,Label3 FROM Register1_master WHERE Label4='" + TextBox1.Text + "' and Label3='" + TextBox2.Text + "'";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
string result= null;
Object value=cmd.ExecuteScalar ();
if ( value != null)
{
result = value.ToString ();
Session["name"] = TextBox1.Text;
Response.Redirect("Main.aspx");
}
else
{
Label3.Text="Invalid username or password";
}
cmd.Connection.Close();
}
after the login from homepage i'll be go on Main.aspx page
my Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperLink link = (HyperLink)Master.FindControl("HyperLink1");
link.Visible = false;
HyperLink link1 = (HyperLink)Master.FindControl("HyperLink2");
link1.Visible = true;
Label masterlbl = (Label)Master.FindControl("Label2");
string login = Convert.ToString(Session["name"]);
Session["name"] = login;
}
}
Have you try like this :
int result= null;
result= = Convert.ToInt32(cmd.ExecuteScalar());
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
Please refer MSDN
I made an application who updates a sqlce database.
The problem is, when I try to delete something it says "InvalidArgument=Value of '1' is not valid for 'index'."
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace Database_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if ( txtEmail.Text == "" || txtQuery.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", txtPrincipal.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#query", txtQuery.Text);
cmd.Parameters.AddWithValue("#subject", txtSubject.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
txtEmail.Clear();
txtPrincipal.Clear();
txtQuery.Clear();
txtSearch.Clear();
txtSubject.Clear();
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown fill the listview with the new information of the database
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
//enable delete button
button3.Enabled = true;
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
string subject = itm.SubItems[3].Text;
txtPrincipal.Text = principalid.ToString();
txtEmail.Text = email.ToString();
txtQuery.Text = query.ToString();
txtSubject.Text = subject.ToString();
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
ListView.SelectedListViewItemCollection items = this.listView1.SelectedItems;
//for (int i = 0; i < listView1.SelectedItems.Count; i++)
foreach(ListViewItem item in items)
{
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
// if button clicked, transfer information out of the records selected to form2
private void button2_Click_1(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to close this application?\nThis will terminate all systems which are active at the moment","Close", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
}
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
private void button4_Click(object sender, EventArgs e)
{
//try
//{
// SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails where principalID like " + txtSearch.Text, conn);
//}
//catch (Exception ex)
//
// MessageBox.Show(ex.Message);
//}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
}
}
It throws the error at
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
Can someone help me please? I've already tried with parameters, but still no luck...
It worked fine before I imported an CSV file into my database with a tool, but the database structure is still the same, so it should be able to delete everything I select.
You can not use * with where condition in delete command ..so TRY like this....
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE query ='" + listView1.SelectedItems[0].Text + "'", conn);
Ignoring the other issues in your code (security of your Sql, etc), I believe this is the specific problem you're asking about.
You're using this:
listView1.SelectedItems[1].Text
... but arrays and lists in C# are zero-absed, and so the first selected item is actually this:
listView1.SelectedItems[0].Text
It's also worth noting that, since you call this in a loop, you will try to delete this single item once for every item in the list. I suspect the loop is redundant or, alternatively, your commented out loop (through each selected item) is what you really want, and in that case you mean this:
listView1.SelectedItems[i].Text
... which would use the text of each item in turn as you loop.