Error: Object reference not set to an instance of an object - asp.net

I'm not really good at programming and I don't know what's happening in my codes, it works well before but now I get this error:
NullReferenceException was unhadled by user code.
Object Reference not set to an instance of an object.
Here's my code:
void GetProfileInfo()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
"WHERE UserID=#UserID";
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Session["userid"].ToString();
SqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
txtFN.Text = data["FirstName"].ToString();
txtLN.Text = data["LastName"].ToString();
txtAddress.Text = data["Address"].ToString();
txtContact.Text = data["ContactNo"].ToString();
txtEmail.Text = data["EmailAddress"].ToString();
}
con.Close();
}

First you have to check all occurrences where Session["userid"] is initialized,
then in order to avoid exception error you have to check this variable value whether is null or wrap the code with try catch finally blocks
Ex:
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT FirstName, LastName, Address, ContactNo, EmailAddress FROM Users " +
"WHERE UserID=#UserID";
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Session["userid"].ToString();
SqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
txtFN.Text = data["FirstName"].ToString();
txtLN.Text = data["LastName"].ToString();
txtAddress.Text = data["Address"].ToString();
txtContact.Text = data["ContactNo"].ToString();
txtEmail.Text = data["EmailAddress"].ToString();
}
}
catch(Exception e)
{
string message = e.Message;
MessageBox.Show(message);
}
finally
{
con.Close();
}

Related

I try to update name record but I can't

protected void submit_Click(object sender, EventArgs e)
{
Label2.Text = Session["id"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = con.CreateCommand();
con.Open();
string UpdateQuery = "Update register set name='" + name.Text + "'where email='" + Session["id"] + "'";
SqlCommand cmd3 = new SqlCommand(UpdateQuery, con);
cmd3.CommandType = CommandType.Text;
con.Close();
}
}
I want to update name record using session for user profile in asp.net.
Try like this:
using (SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
{
string strSQL = "UPDATE register set [name] = #name " +
"WHERE email = #email";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = name.Text;
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["id"].ToString();
conn.Open();
cmd.ExecuteNonQuery();
}
}
The above will dispose/close the connection for you. And this will even close the connection if you have some error in the code.
The above also removes the messy "'" and concatenation in your code (easy to read, and maintain). And by using parameter's the code is also safe from injection.
hence:

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

my asp.net web service code is giving error

hello i have created the code for extracting age from table test
but instead of returning the age it is returning me the following statement
System.Data.SqlClient.SqlDataReader
here is the code
[WebMethod]
public string Getcustomername(string name)
{
SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandText = "SELECT * from test WHERE Name='" + name + "'";
SqlDataReader dt = com.ExecuteReader();
dt.Read();
con.Close();
dt.Close();
return dt.ToString();
any help would be appreciated
Thanks
Instead of returning dt.ToString() you should return the value of a field:
public string GetCustomerAge(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True"))
{
using(SqlCommand com = new SqlCommand())
{
com.Connection = con;
con.Open();
com.CommandText = "SELECT age from test WHERE Name='" + name + "'";
using (SqlDataReader dt = com.ExecuteReader())
{
if (dt.Read())
{
return System.Convert.ToString(dt.GetValue(0));
}
}
}
return "";
}
And please, use parameterized queries - http://en.wikipedia.org/wiki/SQL_injection .

Data list where clause

i am using a datalist to display videos but i am trying to get it working now with the where clasue ...where the name is equal to wrd.mp4 i am getting the following error,
$exception {"The multi-part identifier \"wrd.mp4\" could not be bound."} System.Exception {System.Data.SqlClient.SqlException}
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles where Name=wrd.mp4";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
}
You need to use quotes:
cmd.CommandText = "select Id, Name from tblFiles where Name='wrd.mp4'";

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources