protected void Button1_Click1(object sender, EventArgs e) {
try {
conn.Open();
string idquery = "select top 1 pid from post order by pid desc ";
cmd = new SqlCommand(idquery, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
string p1id = (reader["pid"].ToString());
int pid = Convert.ToInt32(p1id);
TextBox3.Text = (reader["pid"].ToString());
conn.Close();
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
string insertQuery = "insert into post (pid ,pidtype ,title ,question,creationdate) values (#pid,#ptype,#title,#question,#cdate)";
com = new SqlCommand(insertQuery, conn1);
DateTime now = DateTime.Now;
++pid;
com.Parameters.AddWithValue("#pid", pid);
com.Parameters.AddWithValue("#ptype", 1);
com.Parameters.AddWithValue("#title", TextBox2.Text);
com.Parameters.AddWithValue("#question", TextArea1.Text);
com.Parameters.AddWithValue("#cdate", now);
Response.Write("successfull");
Response.Redirect("questions.aspx");
conn1.Close();
} catch (Exception ex) {
Response.Write("error" + ex.ToString());
}
}
this is the code i've written..its not giving any error or exception...bt data is not getting inserted into database
You need to call ExecteNonQuery, afte adding all the parameters:-
com.ExecteNonQuery();
Related
When i search differennt building number in search box it always display first record in the table.
When i tried diffrent building number it does now display it always stay first record of the table.
Can anybody correct my code. Thanks.
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
If the result of 'OleDbCommand.ExecuteReader' is multiple rows
You must call OleDbDataReader.Read() multiple.
example:
while (reader.Read())
{
Console.WriteLine(reader["Building_Name"].ToString());
}
e.g.
textBox4.Text = "";
while (reader.Read())
{
textBox4.Text += reader["Building_Name"].ToString() + ",";
}
It could be because you didn't close the connections. Can you try the code below?
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
reader.Close();
cmd.Dispose();
con2.Close();
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!
this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
I have the following code and I want to show an error message if the id is not found in the table can any body help?
private void button4_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(cs);
string sql = "select * from question where id=#id;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
cmd.Prepare();
cmd.Parameters.AddWithValue("#id", int.Parse(textBox1.Text));
MySqlDataReader rd = cmd.ExecuteReader();
string res = "";
while (rd.Read())
{
if (rd.HasRows==true)
{
res = string.Format("id={0} pid={1} question={2}", rd.GetInt32(0), rd.GetInt32(1), rd.GetString(2));
MessageBox.Show("found" + "\n" + res);
}
MessageBox.Show(" id not found");
}
You need to check for has rows before to start iterating the reader.
if (rd.HasRows==true)
{
while (rd.Read())
{
// Do something here
}
}
else
{
// Show message here
}
I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}