Save picture into specific row in database MySQL using C# - c#

I have project from my lecture to make application that save biodata (Student ID, Name, Departement, etc.) into database. And also I want to save picture profile into database MySQL.
Here's the function to save all data (except picture):
public bool isSignUp (String nim, String nama, String jenisKelamin, String prodi, String angkatan, String pass, String verifPass )
{
if (nim==null || nama==null || jenisKelamin==null || prodi==null || angkatan==null
|| pass==null || verifPass==null)
{
return false;
}
else if(pass.Equals(verifPass)==false)
{
return false;
}
else
{
String query = "insert into dbmahasiswa VALUES (#NIM, #Nama, #JenisKelamin, #ProgramStudi, #Angkatan, #Password)";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Nama", nama);
cmd.Parameters.AddWithValue("#JenisKelamin", jenisKelamin);
cmd.Parameters.AddWithValue("#ProgramStudi", prodi);
cmd.Parameters.AddWithValue("#Angkatan", angkatan);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Warning");
return false;
}
finally
{
connect.Close();
}
return true;
}
}
How to add function to insert picture (that will be profile picture) in this method?

Something like:
string filename = Path.GetFileName(imageToSave.FileName);
string fileExtension = Path.GetExtension(filename);
int fileSize = imageToSave.ContentLength;
if (fileExtension.ToLower() == ".jpg" ) /*you could add a check for what type of image you want to be allowed to save*/
{
Stream stream = postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.ExecuteNonQuery();
}

Related

Insert image in Oracle Database using OleDb from a C# application

I want to insert a PNG image into an OracleDatabase using OleDb and a C# application. The table looks like this:
CREATE TABLE Plant
(
Id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
Name VARCHAR2(50) NOT NULL,
Image BLOB null,
CONSTRAINT plant_pk PRIMARY KEY (Id)
);
Below is the code:
public static void AddBinaryParameterToCommand(OleDbCommand cmd, string parameterColumn, object parameter)
{
if (cmd != null)
{
if (parameter != null && !parameter.ToString().Equals(""))
{
OleDbParameter blobParameter = new OleDbParameter();
blobParameter.OleDbType = OleDbType.LongVarBinary;
blobParameter.Direction = ParameterDirection.InputOutput;
blobParameter.ParameterName = parameterColumn;
blobParameter.Value = parameter;
cmd.Parameters.Add(blobParameter);
}
else
cmd.Parameters.Add(new OleDbParameter(parameterColumn, DBNull.Value));
}
}
public int InsertPlant(string name, byte[] image)
{
int id = 0;
using (var connection = new OleDbConnection(ConnectionString))
{
var commandGetIdText = #"SELECT MAX(id) FROM PLANT";
connection.Open();
using (var command = new OleDbCommand(commandGetIdText, connection))
{
using (var reader = command.ExecuteReader())
{
reader.Read();
id = int.Parse(reader[0].ToString()) + 1;
}
}
var commandText = string.Format("INSERT INTO PLANT(ID,NAME,IMAGE) VALUES (?, ?, ?)");
using (var command = new OleDbCommand(commandText, connection))
{
Utils.AddParameterToCommand(command, "ID", id);
Utils.AddParameterToCommand(command, "NAME", name);
Utils.AddBinaryParameterToCommand(command, "IMAGE", image);
command.ExecuteNonQuery();
connection.Close();
}
}
return id;
}
private void button_UploadMap_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Multiselect = true
};
var path = string.Empty;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = openFileDialog.FileName;
}
else
{
return;
}
byte[] imageArray = File.ReadAllBytes(path);
var palletMapDL = new PalletMapDL("Data Source=192.168.1.21/orcl;Persist Security Info=True; Password=test;User ID=test; Provider=MSDAORA; OLEDB.NET=True; PLSQLRSet=1");
palletMapDL.InsertPlant("Test Plant 01", imageArray);
When execute command.ExecuteNonQuery(); I got this error message:
System.InvalidOperationException: 'Command parameter[2] '' data value
could not be converted for reasons other than sign mismatch or data
overflow.
OleDbException: 'MSDAORA' failed with no error message available,
result code: DB_E_ERRORSOCCURRED(0x80040E21).
Do you know what could be the issue?
Thanks

How to insert null value to image column in SQL Server c#

I have been trying to figure out how to save image into database with both null and image values. For my code it saves the image but if the image is missing it does not save a null value.
public string STDNAME { get; set; }
public string Image { get; set; }
DateTime Date1 = DateTime.Now;
This the code that I used to save the data
public string imagepath { get; set; }
public bool Insert(StudentC c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
byte[] imageBT = null;
FileStream fstream = new FileStream(this.Image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBT = br.ReadBytes((int)fstream.Length);
string sql = "INSERT INTO STUDENT (STDNAME,imagepath,Image,Date) VALUES (#STDNAME,#imagepath,#Image,#Date)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#STDNAME", c.STDNAME);
cmd.Parameters.AddWithValue("#imagepath", c.imagepath);
cmd.Parameters.AddWithValue("#Image", imageBT);
cmd.Parameters.AddWithValue("#Date", Date1);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
Console.WriteLine("\nMessage ---\n{0}", ex.Message);
}
finally
{
conn.Close();
}
return isSuccess;
}
This code is for browsing the image
//browse image
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 2;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox2.Image = Image.FromFile(f.FileName);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.BorderStyle = BorderStyle.Fixed3D;
textBox7.Text = f.SafeFileName.ToString();
string picPath = f.FileName.ToString();
textBox7.Text = picPath;
pictureBox2.ImageLocation = picPath;
}
}
This is the code to supplies the values to store
private void button5_Click(object sender, EventArgs e)
{
c.STDNAME = textBox2.Text;
c.Image = textBox7.Text;
c.imagepath = textBox7.Text;
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("Data has been saved");
//Clear();
}
else
{
// label4.Text = "Data Has not been saved";
MessageBox.Show("Data has not been saved");
}
}
For adding adding null to the image column, make sure you specify the type (e.g. VarBinary) as the example below. In addition, make sure the image column accepts null.
cmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = DBNull.Value;
Moreover, the following approach may lead to the exception further below:
cmd.Parameters.AddWithValue("#Image", DBNull.Value);
--- Exception ---
System.Data.SqlClient.SqlException (0x80131904): Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
**Very Simple Solution
C# Text
query = "insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)"
Sql query Text
insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)
if You use DBNull.Value its save Empty String in Column

checking user name or user email already exists

I am working in a simple registration page where the user can't enter the same user name or email, I made a code that prevent the user from entering the username and it worked but when I tried to prevent the user from entring the same username or email it didn't work.
and my question is, "How can I add another condition where the user can't enter email that already exists?"
I tried to do it in this code, but it did't work:
protected void Button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString );
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con);
SqlCommand cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
Label1.Text = "user name already exists";
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
Label1.Text = "email already exists";
}
else
{
dr1.Close();
dr2.Close();
//add new users
con.Close();
}
}
}
}
but i get this error:
There is already an open DataReader associated with this Command which must be closed first.
Like I said in my comment your design is bad !
First you should have Data Access Layer. This should be project in big solutions but in your case you can put it like new directory. In this directory you create SqlManager class here is the code:
public class SqlManager
{
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["DevConnString"].ConnectionString;
}
}
public static SqlConnection GetSqlConnection(SqlCommand cmd)
{
if (cmd.Connection == null)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static object ExecuteScalar(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataRow GetDataRow(SqlCommand cmd)
{
return GetDataRow(cmd, "Table");
}
public static DataRow GetDataRow(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
if (resultDst.Tables.Count > 0 && resultDst.Tables[0].Rows.Count > 0)
{
return resultDst.Tables[0].Rows[0];
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
After that you should have Business Object Layer. In bigger solution is project in your case directory. If you are in the page TaxesEdit.aspx, you should add Tax.cs class in the BO(business object).
Example of methods for the class, for your first button:
public DataSet GetTaxesByUserName(string userName)
{
SqlCommand cmd = new SqlCommand(#"
select 1 from Table where Name =#UserName");
cmd.Parameters.AddWithValue("#UserName", userName);
return DA.SqlManager.GetDataSet(cmd);
}
You fetch all the needed data in datasets. After that you make checks like taxesDst.Tables[0].Rows.Count > 0 (or == 0)
For Insert you can have method like this:
public virtual void Insert(params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
SqlCommand cmd = new SqlCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
For this you need to have property TableName in the current BO class.
In this case this methods can be used everywhere and you need only one line of code to invoke them and no problems like yours will happen.
You have opened another DataReader inside the First and thats causing the problem. Here I have re-arranged your code a bit
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con),
cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
bool userExists = false, mailExists = false;
using (var dr1 = cmd1.ExecuteReader())
if (userExists = dr1.HasRows) Label1.Text = "user name already exists";
using (var dr2 = cmd2.ExecuteReader())
if (mailExists = dr2.HasRows) Label1.Text = "email already exists";
if (!(userExists || mailExists)) {
// can add User
}
You need to close one datareader before opening the other one. Although it's not how I'd do it, but you can deal with the runtime error by closing the datareader after each IF:
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
string Text = "user name already exists";
}
dr1.Close();
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
string ext = "email already exists";
}
else
{
//add new users
}
dr2.Close();
}
con.Close();
This may work, although there are a few things I would do differently...
protected void Button_Click(object sender, EventArgs e)
{
bool inputIsValid = true;
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var userNameCmd = new SqlCommand("SELECT 1 FROM Table WHERE Name = #UserName", con);
var emailCmd = new SqlCommand("SELECT 1 FROM Table WHERE Email = #UserEmail", con);
con.Open();
userNameCmd.Parameters.AddWithValue("#UserName", Name_id.Text);
emailCmd.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var userNameReader = userNameCmd.ExecuteReader())
{
if (userNameReader.HasRows)
{
inputIsValid = false;
Label1.Text = "User name already exists";
}
}
using (var emailReader = emailCmd.ExecuteReader())
{
if (emailReader.HasRows)
{
inputIsValid = false;
Label1.Text = "Email address already exists";
}
}
if (inputIsValid)
{
// Insert code goes here
}
con.Close();
}
Why don't you do something like this:
[Flags]
public enum ValidationStatus
{
Valid = 0 ,
UserNameInUse = 1 ,
EmailInUse = 2 ,
}
public ValidationStatus ValidateUser( string userName , string emailAddr )
{
ValidationStatus status ;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString ;
using ( SqlConnection con = new SqlConnection( connectionString ) )
using ( SqlCommand cmd = con.CreateCommand() )
{
cmd.CommandText + #"
select status = coalesce( ( select 1 from dbo.myTable t where t.UserName = #UserName ) , 0 )
+ coalesce( ( select 2 from dbo.myTable t where t.UserEmail = #UserEmail ) , 0 )
" ;
cmd.Parameters.AddWithValue( "#UserName" , userName ) ;
cmd.Parameters.AddWithValue( "#emailAddr" , emailAddr ) ;
int value = (int) cmd.ExecuteScalar() ;
status = (ValidationStatus) value ;
}
return status ;
}
Aside from anything else, hitting the DB twice for something like this is silly. And this more clearly expresses intent.
Then you can use it in your button click handler, something like this:
protected void Button_Click( object sender , EventArgs e )
{
string userName = Name_id.Text ;
string emailAddr = Email_id.Text ;
ValidationStatus status = ValidateUser( userName , emailAddr ) ;
switch ( status )
{
case ValidationStatus.Valid :
Label1.Text = "" ;
break ;
case ValidationStatus.EmailInUse :
Label1.Text = "Email address in use" ;
break ;
case ValidationStatus.UserNameInUse :
Label1.Text = "User name in use" ;
break ;
case ValidationStatus.EmailInUse|ValidationStatus.UserNameInUse:
Label1.Text = "Both user name and email address in use." ;
break ;
default :
throw new InvalidOperationException() ;
}
if ( status == ValidationStatus.Valid )
{
CreateNewUser() ;
}
}

How to send uploaded Image as parameter in c# to sql

Here is my code. Error message was
parameter #event_image was not supplied
How to send image name as parameter? If I keep breakpoint it's not even entering into If(fileupload1.HasFile).
I have to store the image in folder and the path must be stored into sql db
{
conn.Open();
string postdate = txtpostdate.Text;
string unpostdate = txtunpostdate.Text;
string name = txtname.Text;
string description = txtdescription.Text;
string country = dropcountry.SelectedItem.ToString();
string multidate = txtstartdae.Text;
string startend = dropstarttime.SelectedItem.ToString();
string drop1m = dropti1m.SelectedItem.ToString();
string dropme1h = droptimeend1h.SelectedItem.ToString();
string drop2m = droptime2m.SelectedItem.ToString();
string notes = txtnotes.Text;
string prevlocation = droplocation.SelectedItem.ToString();
string locationname = txtslocname.Text;
string addres1 = txtsLocAddress1.Text;
string addres2 = txtsLocAddress2.Text;
string city = txtsLocCity.Text;
string state = dropstate.SelectedItem.ToString();
string zipcode = txtsLocZip.Text;
string phonenumber = txtsLocPhone.Text;
string faxnumber = txtsLocFax.Text;
string notes2 = textnotes2.Text;
SqlCommand cmd = new SqlCommand("InsertEvents", conn);
cmd.CommandType = CommandType.StoredProcedure;
//SqlCommand cmd = new SqlCommand("insert into pa_events(event_postdate,event_unpostdate,event_canvisitorsregisters,event_eventname,event_description,event_image,event_multydateevent,event_startdate,event_enddate,event_start,event_end,event_notes,location_name,location_addres1,location_addres2,location_cites,location_state,location_zipcode,location_phonenumber,location_faxnumber,location_notes,event_country) values(#event_postdate,#event_unpostdate,#event_canvisitorsregisters,#event_eventname,#event_description,#event_image,#event_multydateevent,#event_startdate,#event_enddate,#event_start,#event_end,#event_notes,#location_name,#location_addres1,#location_addres2,#location_cites,#location_state,#location_zipcode,#location_phonenumber,#location_faxnumber,#location_notes,#event_country)", conn);
if (fileupload1.HasFile)
{
imagename = fileupload1.FileName;
int length = fileupload1.PostedFile.ContentLength;
fileupload1.SaveAs(Server.MapPath("~\\images\\" + imagename));
s = "~\\images\\" + imagename + "";
}
if (radioyes.Checked == false && !radiono.Checked == false)
{
lblmsg.Text = "Please Select canve Register Yes! or No!";
}
if (radioyes.Checked == true)
{
cmd.Parameters.AddWithValue("#event_canvisitorsregisters", SqlDbType.VarChar).Value = "Y";
}
else
{
cmd.Parameters.AddWithValue("#event_canvisitorsregisters", SqlDbType.VarChar).Value = "N";
}
if (radiomultyyes.Checked == true)
{
cmd.Parameters.AddWithValue("#event_multydateevent", SqlDbType.VarChar).Value = "Y";
}
else
{
cmd.Parameters.AddWithValue("#event_multydateevent", SqlDbType.VarChar).Value = "N";
}
**cmd.Parameters.AddWithValue("#event_image", s);**
cmd.Parameters.AddWithValue("#event_postdate", postdate);
cmd.Parameters.AddWithValue("#event_unpostdate", unpostdate);
cmd.Parameters.AddWithValue("#event_eventname", name);
cmd.Parameters.AddWithValue("#event_description", description);
cmd.Parameters.AddWithValue("#event_country", country);
cmd.Parameters.AddWithValue("#event_startdate", startend);
cmd.Parameters.AddWithValue("#event_enddate", drop1m);
cmd.Parameters.AddWithValue("#event_start", dropme1h);
cmd.Parameters.AddWithValue("#event_end", drop2m);
cmd.Parameters.AddWithValue("#event_notes", notes);
cmd.Parameters.AddWithValue("#location_name", locationname);
cmd.Parameters.AddWithValue("#location_addres1", addres1);
cmd.Parameters.AddWithValue("#location_addres2", addres2);
cmd.Parameters.AddWithValue("#location_cites", city);
cmd.Parameters.AddWithValue("#location_state", state);
cmd.Parameters.AddWithValue("#location_zipcode", zipcode);
cmd.Parameters.AddWithValue("#location_phonenumber", phonenumber);
cmd.Parameters.AddWithValue("#location_faxnumber", faxnumber);
cmd.Parameters.AddWithValue("#location_notes", notes2);
//if (fileupload1.PostedFile != null && fileupload1.PostedFile.FileName != "")
//
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
lblmsg.Text = "record is inserted";
}
else
{
lblmsg.Text = "record is not inserted";
}
conn.Close();
}
The error isn't with your SQL insert, it's with however your file upload is set up. You're getting that error because, as you stated, you're not even entering the if statement that creates the SQL parameter.
Could you post code related to the image upload? That's your root issue.
honestly your code is not clear but hope it works with you:
add parameter with file upload
if (fileupload1.HasFile)
{
imagename = fileupload1.FileName;
int length = fileupload1.PostedFile.ContentLength;
fileupload1.SaveAs(Server.MapPath("~\\images\\" + imagename));
s = "~\\images\\" + imagename + "";
cmd.Parameters.AddWithValue("#event_image", s);
}

Error when does not select data from DDL

I had this message
Input string was not in a correct format
when inserting values into the database. When I checked I have DDL but I did not select value from it so this message appeared, although I make this column in the database to allow NULL value.
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
string File = "~/CvFiles/" + FU_CV.FileName;
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
}
}
private void loadDepts()
{
DDL_Dept.DataSource = d.GetAll();
DDL_Dept.Items.Clear();
DDL_Dept.AppendDataBoundItems = true;
DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
DDL_Dept.DataValueField = "id";
DDL_Dept.DataTextField = "name";
DDL_Dept.DataBind();
}
public bool AddApplicant(string MiddleName, int Dept_ID)
{
SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#Dept_ID", Dept_ID);
System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("#AppID", SqlDbType.Int);
paramter1.Direction = ParameterDirection.Output;
bool rowaffected;
rowaffected = DBHelper.Instance().Insert(cmd);
if (rowaffected == false)
{
AppID = (int)paramter1.Value;
}
return rowaffected;
}
You should check, if DDL_Dept.SelectedValue is a string representation of int. Use int.TryParse method:
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
int dept;
if (int.TryParse(DDL_Dept.SelectedValue, out dept))
app.AddApplicant(txt_Mname.Text, dept);
else
app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}

Categories