Hello .. :)

Im on ma way completing my C# project,, but i have a small issue ..
let me tell you what it is ///

since its complicated to send the whole image to a db i only the send the image name to the database ( table )

FileInfo fn = new FileInfo(txtPath.Text);
                    string p = txtPath.Text;
                    int pos = p.LastIndexOf(".");
                    string ext = p.Substring(pos + 1);
                    string newname = mid + "." + ext;
                    string path = StartPath + "\\images\\" + newname;
                    fn.CopyTo(path);

The images are send to the folder IMAGES as you can see in the code.. nd every image is renamed to the primary key value, in here its MID when its adding .

receiving data its really fine..
but when i delete a record from the database using the C# form
only the image link get removed from the table ..

i have only two solutions in my mind,, once is to delete the image with the record removal or else can i when adding , can i overwrite existing images ? ?

in the above coding im only copying images and when a image exists with the same name the program gets confused . so in order to correct this what should i do.. ? Im waiting a reply from the experts ;)

Thanks in advance :)

Recommended Answers

All 11 Replies

well if your adding a primary key, then there shouldnt be a problem with renaming and adding new pictures, even after deleting pictures...

primary keys, are suppose to be unique and in your database, if you delete lets say record 5... you wont be able to create a new record with that primary key, unless its not auto number...

if thats the case, that the MID is program generated, and not auto number, then deleting the image would be the best bet(or if you want to keep old images, just rename it)..

in try catch block, try to add the image with the new name, if an error is caught, then do the renaming/deletion in the catch block... and if you want to make sure its there afterwards... you can add the finally block at the end to test that the new image has been added

best of luck

Thanks alot Sir ,, MID or the primary key has to be added to the database via a separate form and the user have to type a MID or elz the da primary key :)

do u knw any coding to delete a image ? im a newbie to C# ..
im generating a query to delete the image as everyone does,, what i need is to write some coding in thier to delete the image in the IMAGE Folder with the primary key name ... hope you got what i mean ..

it will be great if you can write down some coding lines :)
Thanks in advance ;)

public bool DeleteFile(string fileToDelete)
{
try
{
if (File.Exists(fileToDelete))
{
File.Delete(fileToDelete);
return true;
}
else
return true;
}
catch (Exception ex)
{
// Log the exception
return false;
}
}

and you could just use the method like

bool del = false;
If(DeleteFile(path))
   //file deleted
else
  //delete failed

Thanks alot sir..
but as i said im a newbie to this ...

if you can, please explain me this stuff...

string fileToDelete ? how can i get the link or the value in the database table to this string ?

im sorry.. im not experienced much with BOOL ,
here is my coding in the mentioned form, if u can please tell me where to paste these codes , according to my knowledge it must be pasted in the onclickevent of the Submit button, please be kind to help me out sir..

using System.IO;
using System.Data;
// importing the OLEDB thing :P
using System.Data.OleDb;
using System.Windows.Forms;

namespace Login_Form
{
    public partial class frmAddMobile : Form
    {
        public frmAddMobile()
        {
            InitializeComponent();
			
			//Set start up path here.
			StartPath = Application.StartupPath;
        }

        // Global Areas Stuff - U Knw :D :D bt dnt ask me haridhaa :D ------------------------------------------------------

        // Global vars - new
        OleDbConnection dbcon;
        OleDbCommand com;
        string sql;
		
		//create string here in class to hold startuppath.
		string StartPath = "":

        // Creating the Onload event
        private void frmAddMobile_Load(object sender, EventArgs e)
        {
			//use startpath string instead of Application.StartupPath;
            string dbloc = StartPath + "\\G2.mdb";
            dbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+dbloc);
        }

        // Method Used to Clear The Text Fields
        private void FormClear()
        {
        }

        // Button & Combo Box Coding Stuff -----------------------------------------------------------------------


        private bool checkid(string id)
        {
           // i removed this code to make code look smaller ;)
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

            if (txtMid.Text == "")

                // i removed if statements to make the coding bit smaller

            else
            {
               
                string mid, mmno, mprice, minfo, manu;
                DateTime doa;

                mid = txtMid.Text;
                mmno = txtModelNo.Text;
                mprice = txtPrice.Text;
                minfo = txtInfo.Text;
                manu = cmbManu.Text;
                doa = DateTime.Now;

                bool id = checkid(mid);

                if (id == false)
                {
			// removed if to make code look smaller ;)
                }

                if (txtPath.Text != "")
                {
                    FileInfo fn = new FileInfo(txtPath.Text);
                    string p = txtPath.Text;
                    int pos = p.LastIndexOf(".");
                    string ext = p.Substring(pos + 1);
                    string newname = mid + "." + ext;
				    //use startpath string instead of Application.StartupPath;
                    string path = StartPath + "\\images\\" + newname;
                    fn.CopyTo(path);

                    sql = "INSERT INTO mobile(MID,MMNO,MPRICE,MINFO,MMANU,MPIC,MDOA) VALUES('" + mid + "','" + mmno + "','" + mprice + "','" + minfo + "','" + manu + "','" + newname + "','" + doa + "')";
                    dbcon.Open();
                    com = new OleDbCommand(sql, dbcon);
                    com.ExecuteNonQuery(); // executing the query ( sending the wehical )
                    MessageBox.Show("Successfully Inserted", "Record Insertion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dbcon.Close();
                    picImage.ImageLocation = txtPath.Text;
                    txtPath.Clear();
                    FormClear();
                    txtMid.Focus();
                }

                else
                {
                    MessageBox.Show("Please Select A Image From The DB", "What the Heck Are u Doin Men ?");
                }

            }
        }

    }
}

Thanks in Advance Sir :)

Take a look,

private bool delImage(string id)
        {
          string query="select mpic from mobile where mid=@p1";
          ....
          OleDbCommand cmd=new OleDbCommand(query,dbcon);
          cmd.Parameters.AddWithValue("@p1",id);

         dbcon.Open();
         object result=cmd.ExecuteScalar();
        dbcon.Close();
 
        if(result!=null) {
            string path= StartPath + "\\images\\" + result.ToString();
            System.IO.File.Delete(path);
            return true;
         }
        return false;
  }

sir,, the method is great ..but in line 4 i see some dots " ................"
what shud i include to it ?

and when shud i call this method sir ?

thanks alot sir..

>.but in line 4 i see some dots " ................" what shud i include to it ?

Remove it.

>when shud i call this method sir ?

Call this method before your delete a database record.

bool id = textBox1.Text
                if (id == false)
                {
                 // what should come here ?
                }

sir.. :(
Finally..how to include method this sir ? i tried so many ways .. ddint work out ,, and i sir.. in the code thier is a line called

@p1

... why is it written for sir ?

Waiting for a reply.. thanks in advance Sir :)

Handle the button's click event.

private void btnDelete_Click(object sender, EventArgs e)
 {
   string id=textbox1.Text;
   delImage(id);
 }
 private bool delImage(string id)
        {
          string query="select mpic from mobile where mid=@p1";
 
          OleDbCommand cmd=new OleDbCommand(query,dbcon);
          cmd.Parameters.AddWithValue("@p1",id);

         dbcon.Open();
         object result=cmd.ExecuteScalar();
         dbcon.Close();
         
        if(result!=null) {
            string path= StartPath + "\\images\\" + result.ToString();
            System.IO.File.Delete(path);
            return true;
         }
        return false;
  }
The connection was not closed. The connection's current state is open.

this error keeps coming when i execute the program.

private void btnDel_Click(object sender, EventArgs e)
        {
         delImage(mobid);
         }

when i try to delete something ,, the above error message comes and highlight the

dbcon.open();

line in the method..

Any Ideas ?

Thanks in advance !

The connection was not closed. The connection's current state is open.

this error keeps coming when i execute the program.

private void btnDel_Click(object sender, EventArgs e)
        {
         delImage(mobid);
         }

when i try to delete something ,, the above error message comes and highlight the

dbcon.open();

line in the method..

Any Ideas ?

Thanks in advance !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.