How to get next data row by hiting on Next button - c#

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

Related

I am not able to rectify this following error : System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'OAT'

protected void btnDeleteVenue_Click(object sender, EventArgs e)
{
try
{
con.Open();
string ddl = DropDownList1.SelectedItem.Value;
string sq = "select venue_name from Venue";
cmd = new SqlCommand(sq, con);
SqlDataReader r = cmd.ExecuteReader();
string dq = null;
if (r.HasRows)
{
while (r.Read())
{
if (ddl.Equals(r.GetValue(0).ToString()))
{
string dq = "DELETE from Venue WHERE venue_name=" + ddl;
//.Close();
cmd = new SqlCommand(dq, con);
cmd.ExecuteNonQuery();
Response.Write("<script> alert('Venue Deleted') </script>");
con.Close();
}
}
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
Change this line to. A string must be quoted.
string dq = "DELETE from Venue WHERE venue_name='" + ddl + "'";

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;
}
}

Error by this code

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");
}

C# Database Insert not working from textbox to listbox

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.

can not Update data in C# Database Access

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();
}

Categories