I'm not a strong coder and quite new to C#. I am having problems with the edit account page of the website that I am trying to create. I am trying to update and insert data into the database and they don't seem to work.
Here's my code:
public partial class EditAccount : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
private readonly object MessageBox;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand com;
string str;
conn.Open();
str = "SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.CardDetailsID, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberID, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'";
com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
TxtEName.Text = reader["MemberName"].ToString();
LblEUser.Text = reader["Username"].ToString();
TxtEEmail.Text = reader["Email"].ToString();
TxtEPhone.Text = reader["Phone"].ToString();
TxtEType.Text = reader["AddressTypeDescription"].ToString();
TxtEHouse.Text = reader["HouseNumber"].ToString();
TxtEA1.Text = reader["AddressLine1"].ToString();
TxtEA2.Text = reader["AddressLine2"].ToString();
TxtECity.Text = reader["City"].ToString();
TxtEPostcode.Text = reader["PostCode"].ToString();
TxtENameOf.Text = reader["NameOfCard"].ToString();
TxtENameOn.Text = reader["NameOnCard"].ToString();
TxtECardNo.Text = reader["CardNumber"].ToString();
TxtEExpDate.Text = reader["CardExpiryDate"].ToString();
TxtECVV.Text = reader["CVV"].ToString();
reader.Close();
conn.Close();
}
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
conn.Open();
SqlDataAdapter str = new SqlDataAdapter ("SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'",conn);
DataSet ds = new DataSet();
str.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
SqlCommand updateCommand = new SqlCommand("UPDATE Member SET MemberName = '" + TxtEName.Text + "', Email = '" + TxtEEmail.Text + "', Phone = '" + TxtEPhone.Text + "'", conn);
SqlCommand updateCommand1 = new SqlCommand("UPDATE Address SET HouseNumber ='" + TxtEHouse.Text + "', AddressLine1 = '" + TxtEA1.Text + "', AddressLine2 = '" + TxtEA2.Text + "', City = '" + TxtECity.Text + "',PostCode = '" + TxtEPostcode.Text + "'", conn);
SqlCommand updateCommand2 = new SqlCommand("UPDATE AddressType SET AddressTypeDescription = '" + TxtEType.Text + "'", conn);
SqlCommand updateCommand3 = new SqlCommand("UPDATE CardDetails SET NameOnCard = '" + TxtENameOn.Text + "', NameOfCard = '" + TxtENameOf.Text + "', CardNumber = '" + TxtECardNo.Text + "', CardExpiryDate = '" + TxtEExpDate.Text + "', CVV = '" + TxtECVV.Text + "'", conn);
updateCommand.ExecuteNonQuery();
updateCommand1.ExecuteNonQuery();
updateCommand2.ExecuteNonQuery();
updateCommand3.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
else
{
SqlCommand insertCommand = new SqlCommand("INSERT INTO AddressType (AddressTypeDescription) VALUES (#AddressTypeDescription)", conn);
insertCommand.Parameters.AddWithValue("#AddressTypeDescription", TxtEType.Text);
insertCommand.ExecuteNonQuery();
SqlCommand insertCommand1 = new SqlCommand("INSERT INTO Address (HouseNumber, AddressLine1, AddressLine2, City, PostCode) VALUES (#HouseNumber, #AddressLine1, #AddressLine2, #City, #PostCode)", conn);
insertCommand1.Parameters.AddWithValue("#HouseNumber", TxtEHouse.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine1", TxtEA1.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine2", TxtEA2.Text);
insertCommand1.Parameters.AddWithValue("#City", TxtECity.Text);
insertCommand1.Parameters.AddWithValue("#PostCode", TxtEPostcode.Text);
insertCommand1.ExecuteNonQuery();
SqlCommand insertCommand2 = new SqlCommand("INSERT INTO CardDetails (NameOnCard, NameOfCard, CardNumber, CardExpiryDate, CVV) VALUES (#NameOnCard, #NameOfCard, #CardNumber, #CardExpiryDate, #CVV)", conn);
insertCommand2.Parameters.AddWithValue("#NameOnCard", TxtENameOn.Text);
insertCommand2.Parameters.AddWithValue("#NameOfCard", TxtENameOf.Text);
insertCommand2.Parameters.AddWithValue("#CardNumber", TxtECardNo.Text);
insertCommand2.Parameters.AddWithValue("#CardExpiryDate", TxtEExpDate.Text);
insertCommand2.Parameters.AddWithValue("#CVV", TxtECVV.Text);
insertCommand2.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
conn.Close();
}
}
Related
I'm a beginner in C# and I wrote a code that connect to my database but It give me a error
I did everything from first but nothing happened
private void btnSubmit_Click(object sender, EventArgs e)
{
string conString = "data source=DESKTOP-D5VFL9P; initial catalog = university; integrated security = True; MultipleActiveResultSets = True;";
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO Persons (PersonID, LastName, FirstName, Age, City) VALUES (" + int.Parse(txtPersonID.Text) + ", '" +
txtLastName.Text + "', '" + txtFirstName.Text + "' ," + int.Parse(txtAge.Text) + ", '" + txtCity.Text + "'", connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
MessageBox.Show("Data inserted");
txtFirstName.Text = "";
txtLastName.Text = "";
txtPersonID.Text = "";
txtAge.Text = "";
txtCity.Text = "";
}
}
}
}
I want to add some values to my database
There should be a ) behind the City. Like txtCity.Text + "')".
I am not recommending this as it is definitely opens a door for SQL Injection Attack but Use below string that will work in your case:
string cmdText = "INSERT INTO Persons(PersonID,LastName,FirstName,Age,City)" +
" VALUES ('" + int.Parse(txtPersonID.Text) + "', " +
"'" + txtLastName.Text + "', " +
"'" + txtFirstName.Text + "' ,'" +
int.Parse(txtAge.Text) + "', '" +
txtCity.Text + "')"
I would do something like this:
using (SqlConnection conn = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT INTO Persons (PersonID,LastName,FirstName,Age,City) VALUES (#PersonID,#LastName,#FirstName,#Age,#City)";
cmd.Parameters.AddWithValue("#PersonID", int.Parse(txtPersonID.Text));
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected > 0)
{
MessageBox.Show("Data inserted");
}
else
{
MessageBox.Show("Failed");
}
conn.Close();
}
I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is.
I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I hope someone can help me find my mistake.
EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.
As MichaĆ Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:
var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = #LastName, FirstName = #FirstName, Title = #Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("#Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}
Few issues with your code:
1) Use using, when working with IDisposable objects, in your case connection and command.
2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")
3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Don't forget to execute the command
Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update CarTb1 set ( #RegNo , #MOdel , #Price , #Available where #Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("#RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("#Brand", combBrand.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#Color", txtColor.Text);
cmd.Parameters.AddWithValue("#Available", combAvailable.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();
Please use the ExecuteNonQuery() instead of SqlDataAdapter:
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.
Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);
I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();
when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();
This question already has answers here:
ExecuteScalar(); With scope_identity() Generating "System.InvalidCastException: Specified cast is not valid" [duplicate]
(5 answers)
Closed 8 years ago.
My code is getting caught right here and I'm not sure why:
int newPersonID = (int)cmd.ExecuteScalar();
It says
Specified cast is not valid.
Can anyone help me out with this error? My PersonID is int type in the database table.
protected void AddNewCustomer(object sender, EventArgs e)
{
string nFirstName = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.FooterRow.FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.FooterRow.FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.FooterRow.FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.FooterRow.FindControl("txtActivityCard")).Text;
string nInitials = ((TextBox)GridView1.FooterRow.FindControl("txtInitials")).Text;
string nBoat = ((TextBox)GridView1.FooterRow.FindControl("txtBoat")).Text;
string nGroup = ((TextBox)GridView1.FooterRow.FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("INSERT INTO Person(FirstName, LastName, Emergency#, Cell#, Age, ActivityCard, CraftType, Initials, Group#) " +
"values(#FirstName, #LastName, #Emergency, #Cell, #Age, #ActivityCard, #Boat, #Initials, #Group);" +
"SELECT SCOPE_IDENTITY();");
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Connection = con;
con.Open();
int newPersonID = (int)cmd.ExecuteScalar();
con.Close();
SqlCommand cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText ="insert into TripSchedule(TripType, PersonID, Time, Date) values ('" + ddlTripType.SelectedItem + "', " + newPersonID + "', '" + ddlTripTime.SelectedItem + "', '" + TextBox1.Text + "');" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = '" + TextBox1.Text + "' and " +
"TripSchedule.Time = '" + ddlTripTime.SelectedItem + "' and TripSchedule.TripType = '" + ddlTripType.SelectedItem + "';";
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Convert.ToInt32(cmd.ExecuteScalar());
Edited: That's right, view the answer in that question thread.
I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}