I have a problem with the button3 it's the UPDATE BUTTON, The message box keeps saying it's a syntax error in the UPDATE Statement. And also if I create another listbox, if I insert a new data, it does not make me insert another data in the 2nd listbox. So if I insert something on the 1st listbox, that index would, for example, be 9, then I would try to insert on the next listbox, but then it would proceed to the index 10.
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != 1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1 (name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Problem 1: you are missing = Symbol while providing input parameters.
Try This:
string q = "update Table1 set [name]= '" + textBox2.Text.ToString() + "' where id= " + listBox1.SelectedItem.ToString();
Problem 2: you are not assigning connection object to `OleDbCommand.
Add This: before executing command
cmd.Connection=cn;
Complete Code:
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex!=-1)
textBox2.Text = l.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1(name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set [name] ='" + textBox2.Text.ToString() + "' where id =" + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.Connection=cn;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Suggestion : your query is open to SQL injection attacks , i would suggest to use Parameterised Queries to avoid them.
Using Parameterised Queries :
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = "update Table1 set [name]=#name where id=#id";
cmd.Parameters.AddWithValue("#name",textBox2.Text.ToString());
cmd.Parameters.AddWithValue("#id",listBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
In the above code (btn3) your are missing id =
Write code like this :
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id=" + listBox1.SelectedItem.ToString();
UPDATE :
My Access query function:
public void ExecuteAccessQurey(string _pQurey)
{
OleDbConnection con = new OleDbConnection("DatabaseConnectionString");
OleDbCommand cmd = new OleDbCommand(_pQurey, con);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
con.Close();
}
Related
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.
When I fill out the form and click registration, it shows an error:
Object reference not set to an instance of an object.
The error is here:
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
Which object must be added to refrence?
Here is the code of the web page:
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
if(IsPostBack)
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] where user_name ='" +
Text_username + "'";
SqlCommand com = new SqlCommand (checkuser , conn);
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1){
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Text_fname.Text = "";
Text_lname.Text = "";
Text_email.Text = "";
Text_password.Text = "";
Text_password_again.Text = "";
Text_username.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string insert = "insert into Table
(user_fname,user_lname,user_email,user_password,user_name) values (#firstName
,#lastName ,#Email ,#passWord ,#userName)";
SqlCommand com = new SqlCommand (insert , conn);
com.Parameters.AddWithValue("#firstName", Text_fname.Text);
com.Parameters.AddWithValue("#lastName", Text_lname.Text);
com.Parameters.AddWithValue("#Email", Text_email.Text);
com.Parameters.AddWithValue("#passWord", Text_password.Text);
com.Parameters.AddWithValue("#userName", Text_username.Text);
com.ExecuteNonQuery();
Response.Write("Registration is successful");
Response.Redirect("Default.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
}
From the error message you have posted, it is clear that the com.ExecuteScalar() is null. Hence, when you call the ToString method on it you get a null reference exception. Since the com.ExecuteScalar() can be null, I suggest you do a check for this.
int temp;
var result = com.ExecuteScalar();
if(result != null)
{
temp = Convert.ToInt32(result.ToString());
}
if (temp == 1)
{
Response.Write("User already exists");
}
I've made a library management system. Put 4 boxes containing the title, author, no of pages and publisher. And then add a button to add it on the database, and I also have 3 listboxes containing the title, author and publisher. It seems that when I accomplished filling up the 4 textboxes and then clicking the button for insert, it's not updating the listboxes and even the database. Nothing is happening. How do you do that?
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public frm1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database2.accdb;Persist Security Info=True";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
lstbxTitle.Items.Clear();
lstbxAuthor.Items.Clear();
lstbxPub.Items.Clear();
try
{
string q = "SELECT * FROM Table2";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lstbxTitle.Items.Add(dr[1].ToString());
lstbxAuthor.Items.Add(dr[2].ToString());
lstbxPub.Items.Add(dr[6].ToString());
}
}
dr.Close();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void lstbxTitle_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
try
{
if (l.SelectedIndex != 1)
{
lstbxTitle.SelectedIndex = l.SelectedIndex;
lstbxAuthor.SelectedIndex = l.SelectedIndex;
lstbxAuthor.Text = lstbxAuthor.SelectedItem.ToString();
lstbxPub.SelectedIndex = l.SelectedIndex;
lstbxPub.Text = lstbxPub.SelectedItem.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtbxAddT.Text != "")
{
string q = "insert into Table2 (Title) values ('" + txtbxAddT.Text.ToString() + "')";
txtbxAddT.Text = null;
}
if (txtbxAddA.Text != "")
{
string q = "insert into Table2 (Author) values ('" + txtbxAddA.Text.ToString() + "')";
txtbxAddA.Text = null;
}
if (txtbxAddNP.Text != "")
{
string q = "insert into Table2 (Page Number) values ('" + txtbxAddNP.Text.ToString() + "')";
txtbxAddNP.Text = null;
}
if (txtbxAddP.Text != "")
{
string q = "insert into Table2 (Publisher) values ('" + txtbxAddP.Text.ToString() + "')";
txtbxAddP.Text = null;
}
loaddata();
}
The problem is
you are not executing your query. It is in the string q, but you are not executing it anywhere.
Create a method:
private void UpdateData(query)
{
try
{
cn.Open();
cmd.CommandText = query; //set query to execute
cmd.ExecuteNonQuery(); //executing the query
cn.Close();
}
catch (Exception ex)
{
}
}
Call this method in every if-statement of method btnAdd_Click:
if (txtbxAddT.Text != "")
{
string q = "insert into Table2 (Title) values ('" + txtbxAddT.Text.ToString() + "')";
UpdateData(q);
txtbxAddT.Text = String.Empty; //Set it to "Empty", Null is not Empty
}
//... and so on for every if check
Best practice advice:
Assigning textbox.Text to "" or null is not a good practice.
Use String.Empty instead.
While checking for textbox.Text for being Empty, never use textbox.Text == null or textbox.Text == "", these are also not the best practices and some times create problems.
Use String.IsNullOrEmpty(textbox.Text) instead.
I want to get next record from table to show as Question. With below code I am not able to get next Question from table.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Quiz_Load();
}
}
private void Quiz_Load()
{
try
{
if (Session["UserQuizID"] != null)
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("select top 0.1 percent QuestionID, Title, Answer1,Answer2,Answer3,Answer4,UserAnswer from [Table_UserAnswer] WHERE UserQuizID = '" + UserQuiz_ID.ToString() + "' AND UserName = '" + mayank.ToString() + "' order by newid()", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["QuestionID"] = dr[0].ToString();
Lbl_QuestionTitle.Text = dr[1].ToString();
RadBut_Answer.Items.Add(dr[2].ToString());
RadBut_Answer.Items.Add(dr[3].ToString());
RadBut_Answer.Items.Add(dr[4].ToString());
RadBut_Answer.Items.Add(dr[5].ToString());
Session["UserAnswer"] = dr[6].ToString();
}
else
{
}
con.Close();
}
else
{
Response.Redirect("Start.aspx");
}
}
catch
{
}
}
protected void RadBut_Answer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int getvalue;
getvalue = Convert.ToInt32(RadBut_Answer.SelectedIndex + 1);
Lbl_SelectedAnsMsg.Text = MessageFormatter.GetFormattedAlertsMessage("Your Selected Answer is : " + getvalue.ToString());
Session["UserAnswer"] = getvalue.ToString();
}
catch
{
}
}
protected void But_Next_Click(object sender, EventArgs e)
{
UpdateUserAns();
if (Session["UserAnswer"] == null)
{
Response.Redirect("Result.aspx");
}
else
{
}
}
private void UpdateUserAns()
{
try
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
string Question_ID = Session["QuestionID"].ToString();
string User_Answer = Session["UserAnswer"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("UPDATE Table_UserAnswer SET UserAnswer='" + User_Answer.ToString() + "' WHERE UserQuizID = '"+ UserQuiz_ID.ToString() +"' AND QuestionID = '"+Question_ID.ToString()+"' AND UserName = '"+mayank.ToString()+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Cancel();
}
catch
{
}
}
hi check this post client here
here you can find solution of your question
Well, I have a simple program that is writing to a Database. I am trying to add validation to the textbox like this,
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length < -1)
{
MessageBox.Show("Don't Leave this field blank!");
}
}
catch
{
//todo
}
}
and My save to database code,
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
But still it is adding blank data to the database and strange thing is in the database I have not allowed null but still data is getting added. Any clues where I am wrong?
I don't see you stopping the database to add empty content. You are validating on the textbox_textchanged event which will only validate the text when someone enters the data. You need to put the validation on button1's click event like this:
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("Null String !!!!!!!!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
//log
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
An empty textbox.Text has zero byte length , not -1.
To be sure the textbox is not empty you should apply the Trim() to the current text
Also there is no need to catch an exception on this code.
Moreover, don't use the TextChanged event to validate the text box.
There is the Validating event for this purpose. (Remember to set CauseValidation=True for the control)
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
e.Cancel = true;
}
}
of course you could move all the validation in the code where do you update the database
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Don't Leave this field blank!");
return;
}
using(SqlConnection con = new SqlConnection(
"Server=DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
{
SqlCommand sql1 = new SqlCommand("INSERT into Book " +
"VALUES(#text1, #text2,#dtValue", con);
sql1.Parameters.AddWithValue("#text1", textBox1.Text);
sql1.Parameters.AddWithValue("#text2", textBox2.Text);
sql1.Parameters.AddWithValue("#dtValue", dateTimePicker1.Value.ToShortDateString());
con.Open();
sql1.ExecuteNonQuery();
this.bookTableAdapter.Fill(this.booksDataSet.Book);
MessageBox.Show("Data Added!");
this.Close();
}
}