Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
namespace CrudOperationOutside
{
    public partial class StudentRegistration : System.Web.UI.Page
    {
        static string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        SqlConnection con = new SqlConnection(CS);
        SqlCommand cmd;
        SqlDataAdapter da;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindQualification();
                BindGender();
                bindHobbies();
                bindGrid();
                Clear();

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string HOB = "";

            for (int i = 0; i < cblHobbies.Items.Count; i++)
            {
                if (cblHobbies.Items[i].Selected == true)
                {
                    HOB += cblHobbies.Items[i].Text + ",";
                }
            }
            HOB = HOB.TrimEnd(',');

            // Get file name from file upload control.
            string FN = Path.GetFileName(fuStudentImage.PostedFile.FileName);

            if (btnSave.Text == "Save")
            {
                // Save images to Application images folder
                fuStudentImage.SaveAs(Server.MapPath("StudentImages" + "\\" + FN));

                SqlCommand cmd = new SqlCommand("sp_Student_Insert", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SName", txtName.Text);
                cmd.Parameters.AddWithValue("@SAge", txtAge.Text);
                cmd.Parameters.AddWithValue("@GID", rblGender.SelectedValue);
                cmd.Parameters.AddWithValue("@QID", ddlQualification.SelectedValue);
                cmd.Parameters.AddWithValue("@Hobbies", HOB);
                cmd.Parameters.AddWithValue("@SFileName", FN);
                con.Open();
                int Total = cmd.ExecuteNonQuery();
                if (Total > 0)
                {
                    lblMessage.Text = "Record is saved successfully";
                }
                con.Close();
                bindGrid();
                Clear();
            }
            else
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("sp_Student_Update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SID",ViewState["SID"]);
                cmd.Parameters.AddWithValue("@SName", txtName.Text);
                cmd.Parameters.AddWithValue("@SAge", txtAge.Text);
                cmd.Parameters.AddWithValue("@GID", rblGender.SelectedValue);
                cmd.Parameters.AddWithValue("@QID", ddlQualification.SelectedValue);
                cmd.Parameters.AddWithValue("@Hobbies", HOB);
                if (FN != "")
                {
                    cmd.Parameters.AddWithValue("@SFileName", FN);
                    File.Delete(Server.MapPath("StudentImages" + "\\" + ViewState["FileName"]));
                    fuStudentImage.SaveAs(Server.MapPath("StudentImages" + "\\" + FN));
                    
                }
                else
                {
                    cmd.Parameters.AddWithValue("@SFileName", ViewState["FileName"]);
                }
                cmd.ExecuteNonQuery();
                con.Close();
            }
            bindGrid();
                                 
        }

        void bindGrid()
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand("select student.SID, student.SName, student.SAge, Gender.GName,Qualification.QName, student.Hobbies, student.SFileName from student join Gender on student.GID = Gender.GId join Qualification on student.QID = Qualification.QId", con);
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                grdStudentDetails.DataSource = ds;
                grdStudentDetails.DataBind();
            }
            con.Close();
        }

        void BindGender()
        {
            con.Open();
            cmd = new SqlCommand("select * from Gender", con); ;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                rblGender.DataSource = ds;
                rblGender.DataValueField = "GID";
                rblGender.DataTextField = "GName";
                rblGender.DataBind();
            }
            con.Close();
        }
        void bindQualification()
        {
            con.Open();
            cmd = new SqlCommand("select * from Qualification", con); ;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddlQualification.DataSource = ds;
                ddlQualification.DataValueField = "QId";
                ddlQualification.DataTextField = "QName";
                ddlQualification.DataBind();
            }
            con.Close();
        }
        void Clear()
        {
            txtName.Text = "";
            txtAge.Text = "";
            btnSave.Text = "Save";
        }

        protected void grdStudentDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EDT")
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Student_Edit", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@SID", e.CommandArgument);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtName.Text = ds.Tables[0].Rows[0]["SName"].ToString();
                    txtAge.Text = ds.Tables[0].Rows[0]["SAge"].ToString();
                    rblGender.SelectedValue = ds.Tables[0].Rows[0]["GID"].ToString();
                    ddlQualification.SelectedValue = ds.Tables[0].Rows[0]["QID"].ToString();
                    string[] arr = ds.Tables[0].Rows[0]["Hobbies"].ToString().Split(',');
                    cblHobbies.ClearSelection();

                    for (int i = 0; i < cblHobbies.Items.Count; i++)
                    {
                        for (int j = 0; j < arr.Length; j++)
                        {
                            if (cblHobbies.Items[i].Text == arr[j])
                            {
                                cblHobbies.Items[i].Selected = true;
                                break;
                            }
                        }
                    }
                    ViewState["FileName"] = ds.Tables[0].Rows[0]["SFileName"].ToString();
                    ViewState["SID"] = e.CommandArgument.ToString();
                    btnSave.Text = "Update";

                }
                con.Close();
            }
            else if (e.CommandName == "DLT")
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Registration_Delete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RID", e.CommandArgument);
                cmd.ExecuteNonQuery();
                con.Close();
                
            }
        }
    }
}

  
                        
                    
   
                        
                    
                    <asp:TemplateField HeaderText="Action">


What I have tried:

When i delete image from image folder then it does not delete file name from database?

Thanks.
Posted
Updated 17-Mar-17 21:51pm
v7
Comments
ZurdoDev 26-Aug-16 14:07pm    
Debug it. What is happening?
Adityakumar2318 26-Aug-16 14:17pm    
I am not getting how to remove file when i click(on delete button)? And where to write the code?

Add this code block in Delete Command Event
C#
string id = e.CommandArgument;
// get the file name from the database
string filename = YourFunctionToGetFileNameFromTable(id);
 File.Delete(Server.MapPath("Files") + "\\"  +  filename));
 
Share this answer
 
Comments
Adityakumar2318 30-Aug-16 13:16pm    
Thanks my issue is resolved.
Karthik_Mahalingam 2-Sep-16 3:58am    
welcome
Your code isn't exactly clear. You posted your button click code but it looks like you are deciding if it is the save button and if not it is the update button.

C#
if (Btnsave.Text == "Save")
           {


Then you've got a row command, which i don't know what that is, but this looks like where your delete logic is as i see a check for EDT (assuming Edit based on stored proc name) otherwise it is the delete command

C#
if (e.CommandName == "EDT")
            {


So with that said, i'll answer this questions with two possibilities.

1) Inside your row command code you've got a call to usp_Registration_Delete. Inside this IF statement is where you should perform your delete operation. Since i don't have access to your computer/code I'm having to make many assumptions. But in your EDT if block, you've got this line

C#
ViewState["Files"] = ds.Tables[0].Rows[0]["Files"].ToString();


If that is the filename you wish to delete. The inside the DLT if block is where you would delete the file.

C#
else if (e.CommandName == "DLT")
            {
var fileToDelete = ds.Tables[0].Rows[0]["Files"].ToString();
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_Registration_Delete",con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RID",e.CommandArgument);
                cmd.ExecuteNonQuery();
                con.Close();

                // Delete The File Here
                File.Delete(fileToDelete);

                Fill_Grid();
            }


2) If the first block of code you posted is the sole button click, then you need to add another if statement to determine if it is delete vs save vs delete

Basically

C#
if (Btnsave.Text == "Save")
{
}
else if (Btnsave.Text == "Update")
{

}
else if (Btnsave.Text == "Delete")
{

}


If this is what needs to happen, then you just take the code from option 1) i posted above, place it inside the Btnsave.Text == "Delete" if block, and then delete the file using the FN variable you posted above (assuming thats the file to delete).

C#
FN = Path.GetFileName(fufile.PostedFile.FileName);
File.Delete(FN);


If none of this steers you in the right direction, i would encourage you to use Improve Question link on your initial post to add more details and information to get the assistance you are looking for.
 
Share this answer
 
Comments
Adityakumar2318 30-Aug-16 13:17pm    
Thanks. My issue is fixed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900