update not working - c#

protected void Page_Load(object sender, EventArgs e)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
private void Display()
{
SqlDataReader reader;
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=Adama6DaY; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT " + " dbo.GMYAKU.NAME, " +"FROM " +
" dbo.GMYAKU " + " WHERE " +
" (dbo.GMYAKU.YKCODE = ('" + txtHidden.Text + "'))",con) ;
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
this.TextBox1.Text = reader["NAME"].ToString();
}
else
{
// 読めないので画面を初期化する
}
cmd.Connection.Close();
cmd.Dispose();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
connetionString = ("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=redacted; Integrated Security=True");
string strSQL ;
strSQL = "UPDATE GMYAKU SET";
strSQL += " NAME = '" + (TextBox1.Text) + "'";
strSQL += " WHERE";
strSQL += " YKCODE= '" + txtHidden.Text + "'";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(strSQL, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
// cnn.Close();
//MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
// MessageBox.Show("Can not open connection ! ");
}
Response.Redirect("Default.aspx");
}

It may be something as simple as not having the control in an update panel to refresh with the new data, but without more information/context it is impossible to tell

I think you need to check the Request.QueryString["YKcode"]; before assigning value to txthidden.text like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString["YKcode"].equals("") && Request.QueryString["YKcode"]!=null)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
}

Related

how to fix "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll"

when I run the code it runs. the login and register form appears. But after entering details when clicking on the register button it shows the error
"An unhandled exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll"
and highlight the con and con.open()
the coding is given below
namespace MovieBookingSystemCSharp
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection **con** = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\dell\Documents\Visual Studio 2015\Projects\MovieBookingSystemCSharp\MovieBookingSystemCSharp\movie.mdf;Integrated Security=True");
**con.Open();**
try
{
string str = "INSERT INTO user1(name,mobile,email,pass) VALUES('" + textBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "'); ";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
//-------------------------------------------//
string str1 = "select max(Id) from user1;";
SqlCommand cmd1 = new SqlCommand(str1, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("New User Registered Successfully..");
Form1 obj = new Form1();
obj.ShowDialog();
this.Hide();
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
}
}
Try to modify the "AttachDbFilename" property without spaces in the path like shown below.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\testuser1\Documents\vs2015\Projects\MovieBookingSystemCSharp\MovieBookingSystemCSharp\movie.mdf;Integrated Security=True");

Problem when paging filter values with Textbox

When I filter some value by an textbox it the first page goes well ofc but the moment that I change to the second page it kinda refreshs and Give me all values again...
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Nome"] == null)
{
Response.Redirect("Login.aspx");
}
if (!Page.IsPostBack)
{
bindgrid();
}
}
private void bindgrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConStr1"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from [Movimentos]";
cmd.Connection = con;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
Sqldata.DataSource = ds;
Sqldata.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
void bindgrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConStr1"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from [Movimentos]";
cmd.Connection = con;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
Sqldata.DataSource = ds;
}
}
protected void Sqldata_PreRender(object sender, EventArgs e)
{
Label1.Text = "Mostrando a página " + (Sqldata.PageIndex + 1).ToString() + " de " + Sqldata.PageCount.ToString();
}
protected void Sqldata_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Sqldata.PageIndex = e.NewPageIndex;
Sqldata.DataSource = (SqlDataSource1);
SqlDataSource1.DataBind();
}
protected void ButnPesquisar_Click(object sender, EventArgs e)
{
string filter = "";
string command = "SELECT * FROM Movimentos WHERE";
if (textDataMovimento.Text != "")
{
filter = filter + " [Data Movimento] LIKE '%" + textDataMovimento.Text + "%' AND";
}
if (TextDataValor.Text != "")
{
filter = filter + " [Data Valor] LIKE '%" + TextDataValor.Text + "%' AND";
}
if (TextDescricao.Text != "")
{
filter = filter + " [Descrição] LIKE '%" + TextDescricao.Text + "%' AND";
}
if (TextValor.Text != "")
{
filter = filter + " [Valor] LIKE '%" + TextValor.Text + "%' AND";
}
if (textTipodeMovimento.Text != "")
{
filter = filter + " [Tipo de Movimento] LIKE '%" + textTipodeMovimento.Text + "%' AND";
}
if (filter.Length > 0)
{
Sqldata.DataSource = SqlDataSource1;
string FinalFilter = filter.Remove(filter.Length - 3);
SqlDataSource1.SelectCommand = command + FinalFilter;
Sqldata.DataBind();
}
else
{
Sqldata.DataBind();
}
}
Any solution? I wasn't able to find any answers cause it looks like no one is using multi textbox's to filter... I Think that's something about the databind right? I tried to take remove change to anothers place but didnt work

Insert and Update Function work on single button click in c#

I am trying to insert and update data using same button. I have created method(uniqueEmail()) to check the email address exist in table or not. Using this method I am trying to insert data if email is not preset.
here is my code please correct me where I am going wrong.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
You need to check for the count of the particular emailId, not the total count.
Modify the code as below:
public static bool uniqueEmail(string email)
{
string stremail;
string querye = "select count(email) as email from register where
email = '" + email + "'";
//Remaining Code
}
public static void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail(TextBox1.Text)) == true)
//Remaining Code
}
#nirmala you should replace method
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Two Things need to be done
Pass the Email Id while calling
if (uniqueEmail()==true)
To
if (uniqueEmail(TextBox1.Text)==true)
And in uniqueEmail method chenage the query ()include where condition as below
public bool uniqueEmail(email)
{
string stremail;
string querye = "select count(email) as email from registeruser where email='" + email + "'";
//your remaining code
}
Hi Nirmala your code is correct only you need to put where clause to find the email id already exist in the Database.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser where email = '" +TextBox1.Text+ "'";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}

Gridview Edit Delete and Update in ASP.NET

I tried Implementing the code for Edit and Update button for gridview but it doesn't seems working for me. Add button working well but delete and update do not working. During runtime error the error is "An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Unknown column 'p001' in 'where clause'"
Note: type of P_Id in the database is varchar(10), name varch(100), level varchar, value varchar
public partial class ManagePractice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
TextBox txtID = (TextBox)GridView1.FooterRow.FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.FooterRow.FindControl("txtSubject");
RadioButtonList Level = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList1");
AddPractice(txtID.Text.Trim(), txtSubject.Text.Trim(), Level.Text.Trim(), PType.Text.Trim());
BindData();
}
private void AddPractice(string P_Id, string subject, string level, string type)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "insert into practice(P_Id,name,level,value) values ('" + P_Id + "','" + subject + "','" + level + "','" + type + "')";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select P_Id,level,name,value from practice", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = (GridView1.DataKeys[e.RowIndex].Value.ToString ());
DeletePractice(id);
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubject");
// TextBox Level1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtlevel");
// TextBox PType1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPType1");
RadioButtonList Level = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
UpdatePractice( txtID.Text , txtSubject.Text, Level.Text, PType.Text);
GridView1.EditIndex = -1;
BindData();
}
private void UpdatePractice( string P_Id, string name, string level, string value)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + " WHERE P_Id=" + P_Id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void DeletePractice(string id)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "DELETE FROM practice WHERE P_Id=" + id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
First sight:
Since P_Id column has VARCHAR(10) datatype, I figured out you forget to include some additional apostrophes on UPDATE & DELETE clause. The correct form of SQL statements should be this (notice additional apostrophe signs around P_Id column):
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + "' WHERE P_Id= '" + P_Id + "'";
and
string query = "DELETE FROM practice WHERE P_Id='" + id + "'";
Only string values require apostrophes around them, numbers do not.

Object reference not set to an instance of an object for asp.net

protected void Page_Load(object sender, EventArgs e)
{
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr; // to hold reference of datareader returned
//prepare a place - datatable to hold the data
DataTable dt = new DataTable();
//setting up command
cmd.CommandText = sql;
cmd.Connection = con;
//connection and execute command
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr); // copy data from datareader to datatable
string pwdcheck;
pwdcheck = dt.Rows[0]["password"].ToString();
if (tb_verify.Text.Equals(pwdcheck))
{
string password = tb_pwd.Text;
sql = "Update Profile set password ='" + password + "'";
sql = sql + "where userid = '" + Session["userid"] + "'";
cmd.CommandText = sql;
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
lb_msg.Text = "Password changed succesfully";
}
catch (Exception ex)
{
lb_msg.Text = "Problems encountered " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
else
lb_msg.Text = "Old password Incorrect";
}
protected void lblClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Clear(); // This may not be needed -- but can't hurt
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
}
}
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
there is an error at the line above with
Object reference not set to an instance of an object the change password feature was working before.
In your case Session["userid"] must be NULL,handle it

Categories