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
}
Related
I'm facing a minor problem and I'll tell you all the details below. If you help me I would be very happy.
I have 3 tables in my database as "tbl_User", "tbl_City", "tbl_Town".
My "tbl_User" table:
userid int [PK],
email nvarchar(50),
password nvarchar(50),
city int,
town int
My "tbl_City" table:
cityno int [PK],
cityname nvarchar(50)
My "tbl_Town" table:
townno int,
townname nvarchar(50),
cityno int
As you can see, "tbl_City" and "tbl_Town" tables are related to each other. This means there are towns connected to every city.
While the user is registering on the site, he must choose city and town. So I can save city and town as number in "tbl_User".
What I want to do is: When the user goes "profile.aspx", I want the city and town name to be seen in DropDownLists selectively. And when user click DropDownListCity; I want all the other cities to appear at the same time. And when user click DropDownListTown; I want showing all towns connected to the selected city.
My code bring the city selected in the "tbl_User" and when I click DropDownListCity I can see all other cities. There is no problem here. But my code doesn't bring the town selectively. I get en error: 'System.NullReferenceException'. I think it's because the city is chosen in DropDownList but program does not see the city selected.
My code is as follows:
Fonksiyon function = new Fonksiyon();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
GetTown();
GetCityAndTownSelectively();
}
}
private void GetCityAndTownSelectively()
{
if (Session["userid"] != null)
{
DataRow dr = function.GetDataRow("SELECT tbl_City.cityno, tbl_City.cityname, tbl_Town.townno, tbl_Town.townname FROM tbl_User LEFT JOIN tbl_City on tbl_City.cityno = tbl_User.city LEFT JOIN tbl_Town on tbl_Town.townno = tbl_User.town WHERE userid=" + Session["userid"].ToString());
if (dr == null)
{
Response.Redirect("default.aspx");
}
else
{
DropDownListCity.ClearSelection();
DropDownListCity.Items.FindByValue(dr[0].ToString()).Selected = true;
DropDownListTown.ClearSelection();
DropDownListTown.Items.FindByValue(dr[2].ToString()).Selected = true;
}
}
else
{
Response.Redirect("default.aspx");
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + DropDownListCity.SelectedValue + "'", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(mesaj);
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
GetTown();
}
Program gives the error in the following line: DrpDwnLstTown.Items.FindByValue(dr[2].ToString()).Selected = true; And I think i guess i found the cause of the error: When I changed my GetTown methods SQL query like this: SELECT * FROM tbl_Town my code brings town selectively but when I click DropDownListTown I see all towns. The problem is I have to only see the town connected to the city.
This is the full code you need.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
if (DropDownListCity.Items != null)
{
GetTown(Convert.ToInt32(DropDownListCity.SelectedValue.ToString()));
}
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City order by cityName", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown(Int32 selectedCityNo)
{
if (selectedCityNo == 0)
{
DropDownListTown.Visible = false;
}
else
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + selectedCityNo.ToString() + "' order by townname", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCity = (DropDownList)sender;
string selectedID = ddlCity.ID;
DropDownList ddlSelectedCity = (DropDownList)FindControl(selectedID);
GetTown(Convert.ToInt32(ddlSelectedCity.SelectedValue.ToString()));
}
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();
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 am trying to use a LInklabel to open a hyperlink i have on my access database. However, this is the first time using a linklabel. Any suggestions would be great!
con.Open();
str = "Select * from loc where link ='" + facility+ "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
linkLabel1.Text = dr.GetString(17);
}
The following code works for me:
private void Form1_Load(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, website FROM Clients WHERE ID = 1";
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
String fName = rdr["FirstName"].ToString();
String url = rdr["website"].ToString();
if (url.Substring(0,1).Equals("#"))
{
// remove leading and trailing hash marks from URL
// as retrieved from a Hyperlink field in Access
url = url.Substring(1, url.Length - 2);
}
linkLabel1.Text = String.Format("Link to {0}'s website", fName);
linkLabel1.Links.Add(0, linkLabel1.Text.Length, url);
}
con.Close();
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string target = e.Link.LinkData as string;
System.Diagnostics.Process.Start(target);
}
i have registration page and i want to check that username is already exist in database or not in 3 tier architecture.
MyRegistration.cs:
public static int checkusername(string user_txt)
{
int id2 = 0;
string selectstr = "select * from xyz where UserName = '" + user_txt + " ' ";
id2 = DataAccessLayer.ExecuteReader(selectstr);
return id2;
}
and the code behind onclick event of textbox:
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
int id = xyz.checkusername(txt_username.Text.Trim());
if (id > 0)
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
DataAccessLayer:
public static int ExecuteReader(string Query)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = Query;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
I have edited some of your codes try like below... it will help you...
Text change Event :
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
if (xyz.checkusername(txt_username.Text.Trim()))
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
Check Username :
public bool CheckUsername(string user_txt)
{
bool Result;
Result = DataAccessLayer.ExecuteReader(user_txt);
return Result;
}
Excute Reader :
public bool ExecuteReader(string user_txt)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("select * from xyz where UserName = #UserID", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserID";
param.Value = user_txt;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
return true;
else
return false;
}
Usually if the "select query" doesn't find a userName with the parameter user_txt you'll id2 will be end up with the value -1. So the appropriate code would be:
if (id ==-1)
{
lblStatus.Text = "UserName Available";
}
if (id>0)
{
lblStatus.Text = "UserName Already Taken";
}
By the way, your code is highly insecure and your database can be easily attacked using SQL Injection I'd recommend you to understand this issue and add parameters to the query to prevent it. C# has its ways to implement this. Don't try to fix the access to the database, just start from scrath keeping in mind SQL Injection.
As others have mentioned, this approach has potentially serious security issues.
However, your problem may lie here user_txt + " ' ". The spaces around the second ', specifically the one before it may lead to the usernames not matching as expected.