PosterDirectory returns null - c#

I declared the variable PosterDirectory here
SqlConnection con = new SqlConnection(Helper.GetConnectionString());
String PosterDirectory;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Role"].ToString() != "Admin")
{
Session.Clear();
Response.Redirect("Default.aspx");
}
if (!IsPostBack)
{
GetEvent(int.Parse(Request.QueryString["EventID"].ToString()));
}
}
Supposedly PosterDirectory would be given a value within the GetEvent function.
void GetEvent(int EventID)
{
con.Open();
SqlCommand com = new SqlCommand(
"select * from event where EventID = #EventID", con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = EventID;
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
//Fill in the input fields based on the EventID
txtName.Text = reader["Name"].ToString();
txtVenue.Text = reader["Venue"].ToString();
txtStreet.Text = reader["Street"].ToString();
txtCity.Text = reader["City"].ToString();
txtCountry.Text = reader["Country"].ToString();
txtMap.Text = reader["Map"].ToString();
txtStartDate.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).ToString("yyyy-MM-dd");
txtStartTime.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).TimeOfDay.ToString();
txtEndDate.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).ToString("yyyy-MM-dd");
txtEndTime.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).TimeOfDay.ToString();
PosterDirectory = reader["Poster"].ToString();
txtDesciption.Text = reader["Description"].ToString();
}
con.Close();
}
I will use the String PosterDirectory later on for my SQL Parameter to retrieve the filepath of a photo.
protected void btnUpdate_Click(object sender, EventArgs e)
{
//Get the Date and Time Strings
DateTime DateStarted = Convert.ToDateTime(txtStartDate.Text);
TimeSpan TimeStarted = TimeSpan.Parse(txtStartTime.Text);
DateTime DateEnded = Convert.ToDateTime(txtEndDate.Text);
TimeSpan TimeEnded = TimeSpan.Parse(txtEndTime.Text);
DateTime DateTimeStarted = DateStarted + TimeStarted;
DateTime DateTimeEnded = DateEnded + TimeEnded;
//Get the DateTimeCreated
DateTime DateTimeLastUpdated;
con.Open();
//if (fuPoster.HasFile)
{
SqlCommand com = new SqlCommand(
"update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Poster=#Poster, Description=#Description where EventID=#EventID",
con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
DateTimeLastUpdated = DateTime.Now;
if (fuPoster.HasFile)
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = "images/" + fuPoster.FileName;
fuPoster.SaveAs(Server.MapPath("images/" + fuPoster.FileName));
}
else
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = PosterDirectory;
}
com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
com.ExecuteNonQuery();
con.Close();
//Auditing Event
AuditEvent(DateTimeLastUpdated);
Response.Redirect("Event.aspx");
}
//else
//{
// SqlCommand com = new SqlCommand(
// "update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Description=#Description where EventID=#EventID",
// con);
// com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
// com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
// com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
// com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
// com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
// com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
// com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
// com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
// com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
// com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
// com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
// DateTimeLastUpdated = DateTime.Now;
// com.ExecuteNonQuery();
// con.Close();
// //Auditing Event
// AuditEvent(DateTimeLastUpdated);
// Response.Redirect("Event.aspx");
//}
}

Members aren't persisted between requests. The Form class is only valid for a single request.
For context, read up on the ASP.NET Page Life Cycle.
You could put your value into a hidden form field or the view state.

Related

how to call validation function while saving data in database?

I want to use strong password in my program. So I searched for strong password validation but I didnt understand how to call that function while saving.
This is the function I want to use for password validation:
private bool ValidatePassword(string password, out string ErrorMessage)
{
var input = password;
ErrorMessage = string.Empty;
if (string.IsNullOrWhiteSpace(input))
{
throw new Exception("Password should not be empty");
}
var hasNumber = new Regex(#"[0-9]+");
var hasUpperChar = new Regex(#"[A-Z]+");
var hasMiniMaxChars = new Regex(#".{8,15}");
var hasLowerChar = new Regex(#"[a-z]+");
var hasSymbols = new Regex(#"[!##$%^&*()_+=\[{\]};:<>|./?,-]");
if (!hasLowerChar.IsMatch(input))
{
ErrorMessage = "Password should contain At least one lower case letter";
return false;
}
else if (!hasUpperChar.IsMatch(input))
{
ErrorMessage = "Password should contain At least one upper case letter";
return false;
}
else if (!hasMiniMaxChars.IsMatch(input))
{
ErrorMessage = "Password should not be less than or greater than 12 characters";
return false;
}
else if (!hasNumber.IsMatch(input))
{
ErrorMessage = "Password should contain At least one numeric value";
return false;
}
else if (!hasSymbols.IsMatch(input))
{
ErrorMessage = "Password should contain At least one special case characters";
return false;
}
else
{
return true;
}
}
The save button code:
private void btnSave_Click(object sender, EventArgs e) {
var data = DBConnection.DBConnect();
SqlCommand cmd = new SqlCommand("Insert_Users", data);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StaffName", SqlDbType.VarChar).Value = txtStaffName.Text;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("#Phoneno", SqlDbType.NVarChar).Value = txtPhoneNo.Text;
cmd.Parameters.Add("#Admin", SqlDbType.Char).Value = chkIsAdmin.CheckState == CheckState.Checked ? 1 : 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
MessageBox.Show("Saved Sucessfully");
LoadUsers();
}
Can someone give me an idea how I can use this function to perform password validation, please?
Maybe I do not get the problem but it's that simple?:
private void btnSave_Click(object sender, EventArgs e) {
var error = string.Empty;
if(ValidatePassword(txtPassword.Text, error))
{
var data = DBConnection.DBConnect();
SqlCommand cmd = new SqlCommand("Insert_Users", data);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StaffName", SqlDbType.VarChar).Value = txtStaffName.Text;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("#Phoneno", SqlDbType.NVarChar).Value = txtPhoneNo.Text;
cmd.Parameters.Add("#Admin", SqlDbType.Char).Value = chkIsAdmin.CheckState == CheckState.Checked ? 1 : 0;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
MessageBox.Show("Saved Sucessfully");
LoadUsers();
}
else
{
throw new Exception(error); // Or Console.WriteLine(error) or whatever
}
}

submit form even is invalid c#

I have a problem when click on submit button. the data still insert into database even though there is an invalid data.
public partial class surveyCreate : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
private string lblTextMessage;
protected void Page_Load(object sender, EventArgs e)
{
btnSubmitSurvey.Attributes.Add("onclick", "return PostPage();");
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
if (!IsPostBack)
{
int a_unit = 0;
string username = (string)Session["Username"];
string query5 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd5 = new SqlCommand(query5, con);
SqlDataReader dr5 = cmd5.ExecuteReader();
if (dr5.Read())
{
a_unit = Convert.ToInt32(dr5["a_unit"]);
}
dr5.Close();
con.Close();
string queryA = "";
string queryB = "";
string queryC = "";
queryA = "SELECT * FROM tblUnit WHERE u_master = " + a_unit;
queryB = "SELECT * FROM tblProject ";
queryC = "SELECT * FROM tblSurveyTemplate where st_template = " + a_unit;
BindDropDownList(ddlunit, queryA, "u_name", "u_id", "SELECT UNIT");
//BindDropDownList(project, queryB, "pro_name", "pro_id", "SELECT PROJECT");
BindDropDownList(ddlTemplate, queryC, "st_name", "st_id", "SELECT TEMPLATE");
ddlproject.Enabled = false;
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
// string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void unit_SelectedIndexChanged(Object sender, EventArgs e)
{
ddlproject.Enabled = true;
int u_id = int.Parse(ddlunit.SelectedItem.Value);
string query = "Select pro_id, pro_name from tblProject WHERE u_id=" + u_id;
BindDropDownList(ddlproject, query, "pro_name", "pro_id", "SELECT PROJECT");
}
protected void ddlTemplate_SelectedIndexChanged(Object sender, EventArgs e)
{
int st_id = int.Parse(ddlTemplate.SelectedItem.Value);
SqlDataSourceQuestions.SelectCommand = "SELECT sq_id, sq_question FROM tblSurveyQuestions WHERE st_id=" + st_id;
string query = "SELECT * FROM tblSurveyTemplate WHERE st_id=" + st_id;
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
LabelComment.Text = dr["st_comment"].ToString();
LabelIntro.Text = dr["st_intro"].ToString();
}
dr.Close();
con.Close();
if (st_id != 0)
PanelA.Visible = true;
else
PanelA.Visible = false;
}
/**
protected void project_SelectedIndexChanged(Object sender, EventArgs e)
{
project.Enabled = true;
project.Items.Clear();
project.Items.Insert(0, new ListItem("SELECT PROJECT", "0"));
int unitId = int.Parse(unit.SelectedItem.Value);
if (unitId > 0)
{
string query = string.Format("Select pro_id, pro_name from tblProject where pro_id = {0} ", unitId);
BindDropDownList(project, query, "pro_name", "pro_id", "SELECT PROJECT");
project.Enabled = true;
}
}
static int i = 0;
protected void btn_addp_Click(object sender, EventArgs e)
{
int j = 0;
i++;
for (j = 0; j < i; j++)
{
TextBox tb = new TextBox();
tb.Width = 350;
tb.ID = "MP" + j.ToString();
ph.Controls.Add(tb);
}
}
*/
protected void btn_addp_Click(object sender, EventArgs e)
{
int index = pnlTB.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox tb = new TextBox();
tb.ID = id;
tb.Width = 350;
pnlTB.Controls.Add(tb);
Literal lt = new Literal();
lt.Text = "<div style=height:3px ></div>";
pnlTB.Controls.Add(lt);
pnlTB.Controls.Add(new LiteralControl("<div style=height:3px ></div>"));
}
protected void GetTextBoxValues(object sender, EventArgs e)
{
}
//duplicate email
protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
{
//TextBox[] participant = { participant1, participant2, participant3 };
//if (participant1.Text == participant2.Text || participant2.Text == participant3.Text || participant1.Text == participant3.Text)
//{
// cvSubmit.ErrorMessage = "* Duplicate email! Please enter different email. ";
// cvSubmit.Focus();
// e.IsValid = false;
//}
}
here is the code for submit
protected void btnSubmitSurvey_Click(object sender, EventArgs e)
{
string a_id = "";
string username = (string)Session["Username"];
string query4 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd4 = new SqlCommand(query4, con);
SqlDataReader dr4 = cmd4.ExecuteReader();
if (dr4.Read())
{
a_id = dr4["a_id"].ToString();
}
dr4.Close();
con.Close();
if (Page.IsValid)
{
con.Open();
string query = "CreateSurvey";
string query1 = "ListParticipant";
int surveyID;
DateTime date_now = DateTime.Now;
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sd_id", SqlDbType.Int, 0, "sd_id");
cmd.Parameters["#sd_id"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#sd_title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.Add("#sd_unit", SqlDbType.NVarChar).Value = ddlunit.SelectedValue;
cmd.Parameters.Add("#sd_project", SqlDbType.NVarChar).Value = ddlproject.SelectedValue;
cmd.Parameters.Add("#sd_year", SqlDbType.NVarChar).Value = txtYear.Text;
cmd.Parameters.Add("#st_id", SqlDbType.NVarChar).Value = ddlTemplate.SelectedValue;
cmd.Parameters.Add("#sd_datecreated", SqlDbType.DateTime).Value = date_now;
cmd.Parameters.Add("#sd_createdBy", SqlDbType.NVarChar).Value = a_id;
cmd.ExecuteNonQuery();
surveyID = (int)cmd.Parameters["#sd_id"].Value;
//validate email
bool email = Regex.IsMatch(participant.Text.Trim(), "\\w+([-+.']\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
if (!email)
{
lbl2.Text = "Invalid email address";
return;
}
else
{
lbl2.Text = "";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = participant.Text;
cmd1.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd1.ExecuteNonQuery();
}
foreach (TextBox textBox in pnlTB.Controls.OfType<TextBox>())
{
if (textBox.Text != "")
{
SqlCommand cmd2 = new SqlCommand(query1, con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = textBox.Text;
cmd2.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd2.ExecuteNonQuery();
}
}
string message = "Your survey details has been saved.";
string url = "surveyConfirm.aspx?surveyId=" + surveyID;
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += url;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
con.Close();
}
else
{
lbl2.Text = "Fill up the information required";
}
}
}
someone please help me to solve this problem. thank you

Need Id to Upload excel sheet in the gridview

I have a feature to upload the Excel sheet data into the gridview. The data will get inserted into the child table of database.
Now, My issue here is. One of the column has a relation with the Master table.
So, untill and unless I add that column ID which has a relation it gives me error as
The Student_id column was not supplied
Here is my code
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select count(email) from tbl_student_report where email=#email", con);
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = dt.Rows[i]["Email Id"].ToString();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Duplicate user in the sheet, Sheet will not be uploaded..!!!');window.location ='csrstudentprogress.aspx';", true);
continue;
}
cmd = new SqlCommand("INSERT INTO tbl_student_report(NgoId,student_id,name,email,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#NgoId,#student_id,#name,#email,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = dt.Rows[i]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = dt.Rows[i]["StudentId"].ToString();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
Please suggest what to do in this case, because User will not add student_id in the excel sheet and upload.
I am using sql-server 2008
How to achieve this ??
I got it done by trying myself like below:-
Helper class
public static DataTable GetUserIdByName(string userName,string userType)
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_User WHERE Username=#Username AND UserType=#UserType", con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("#UserType", SqlDbType.VarChar).Value = userType;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
And calling the Class in the Export function did the job:-
DataTable table = GeneralHelper.GetUserIdByName(Session["User"].ToString(), Session["UserType"].ToString());
for (int i = 0; i < dt.Rows.Count; i++)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
if (table != null && table.Rows.Count > 0)
{
string StudentId = GetNgoIdStudentId(dt.Rows[i]["Email Id"].ToString());
if (StudentId != null)
{
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_student_report(student_id,name,emailid,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#student_id,#name,#emailid,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = table.Rows[0]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = StudentId;
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#emailid", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
if (string.IsNullOrEmpty(dt.Rows[i]["Date Of Record"].ToString()))
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
}
if (string.IsNullOrEmpty(dt.Rows[i]["Modified Date"].ToString()))
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
}
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Student not found');", true);
}
}
else
{
//Error
}
}
}

why does it keep on saying "cannot find table 0"?

i'm creating a system that has an add-edit-delete function but whenever i try to edit a value from my ms sql server 2005 it keeps on telling me "cannot find table 0". below is my code i'm using visual studio c# 2008:
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter dad = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(dad);
dad.UpdateCommand = new SqlCommand("UPDATE tblSchools SET Number = #id, School_Name = #school, Province = #prov, City = #city, Brgy = #brgy, Lot_Num = #lot, Area = #area, Mem_Date_Rec = #date, Cenro = #cenro", conn);
dad.UpdateCommand.Parameters.Add("#school", SqlDbType.VarChar).Value = textBox1.Text;
dad.UpdateCommand.Parameters.Add("#prov", SqlDbType.VarChar).Value = comboBox1.Text;
dad.UpdateCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox2.Text;
dad.UpdateCommand.Parameters.Add("#brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.UpdateCommand.Parameters.Add("#lot", SqlDbType.NVarChar).Value = textBox5.Text;
dad.UpdateCommand.Parameters.Add("#area", SqlDbType.Decimal).Value = textBox6.Text;
dad.UpdateCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.UpdateCommand.Parameters.Add("#cenro", SqlDbType.NVarChar).Value = textBox8.Text;
dad.UpdateCommand.Parameters.Add("#id", SqlDbType.Int).Value = ds.Tables[0].Rows[tblNamesBS.Position][0];
conn.Open();
dad.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
above the code i made a global function
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
BindingSource tblNamesBS = new BindingSource();
what seems to be the problem here??
oh and to add up i made a datagridview that has a double click event, below is my code:
private void dg_DoubleClick(object sender, EventArgs e)
{
try
{
button2.Visible = true;
button5.Visible = true;
DataTable dt = new DataTable();
SqlDataAdapter dad = new SqlDataAdapter("SELECT * FROM tblSchools WHERE Number ="+
Convert.ToInt16(dg.SelectedRows[0].Cells[0].Value.ToString()) + "", conn);
dad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
comboBox1.Text = dt.Rows[0][2].ToString();
textBox2.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
//dateTimePicker1.Value = dt.Rows[0][7];
textBox8.Text = dt.Rows[0][8].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
will this code affect my edit?
You have declared an empty data set
DataSet ds = new DataSet();
And later you try to access Table[0] in it but there isn't one defined.

Updating records

private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True"))
{
string sqlQuery = #"UPDATE cottonpurchase SET #slipNo, #basicprice, #weight, #totalamountbasic, #premium, #totalamountpremium, #totalamountpaid, #yeildestimates WHERE farmercode = #farmercode";
{
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
cmd.Parameters.Add("#slipNo", SqlDbType.Int).Value = TxtSlipNo.Text;
cmd.Parameters.Add("#basicprice", SqlDbType.Int).Value = TxtBasicPrice.Text;
cmd.Parameters.Add("#weight", SqlDbType.Int).Value = TxtWeight.Text;
cmd.Parameters.Add("#totalamountbasic", SqlDbType.Int).Value = TxtTotalAmountBasic.Text;
cmd.Parameters.Add("#premium", SqlDbType.Int).Value = TxtPremium.Text;
cmd.Parameters.Add("#totalamountpremium", SqlDbType.Int).Value = TxtTotalAmountPremium.Text;
cmd.Parameters.Add("#totalamountpaid", SqlDbType.Int).Value = TxtTotalAmountPaid.Text;
cmd.Parameters.Add("#yeildestimates", SqlDbType.Int).Value = TxtYeildEstimates.Text;
sqlConn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
It's giving me an error even though everything seems fine with my code:
error : incorrect syntax near ','
You need to specify column names that you are trying to set.
string sqlQuery = #"
UPDATE cottonpurchase
SET
slipNo = #slipNo,
basicprice= #basicprice,
weight = #weight,
totalamountbasic = #totalamountbasic,
premium = #premium,
totalamountpremium = #totalamountpremium,
totalamountpaid = #totalamountpaid,
yeildestimates = #yeildestimates
WHERE farmercode = #farmercode";
Also, you didn't provide #farmercode parameter:
cmd.Parameters.AddWithValue("#farmercode", <someValue>);
You forgot to mention the column names in the set.
string sqlQuery = #"UPDATE cottonpurchase SET slipNo=#slipNo, basicprice=#basicprice, ... WHERE farmercode = #farmercode";

Categories

Resources