How to connect to SQL Server using ADO.Net - asp.net

This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.

Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]

Related

Restricting user access in asp.net

I am working on asp.net application. I want only logged in users to access the Game page. When the users log in, the id and pass are authenticated from the SQL then they are logged in. and I want the logged in users to have an access to Games.aspx.
Here is the login code,
public partial class Login : System.Web.UI.Page
{
//"Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
lbInfo.Enabled = false;
}
public bool IsAuthenticated
{
get { return Convert.ToBoolean(Session["sIsAuthenticated"] ?? false); }
set { Session["sIsAuthenticated"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = "Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("spStudentProfile", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("RegNo", TextBox2.Text);
SqlParameter p2 = new SqlParameter("Password", TextBox1.Text);
com.Parameters.Add(p1);
com.Parameters.Add(p2);
con.Open();
SqlDataReader rd = com.ExecuteReader();
if (rd.HasRows)
{
IsAuthenticated = true;
rd.Read();
Response.Redirect("~/Games.aspx");
}
else
{
IsAuthenticated = false;
lbInfo.Enabled = true;
lbInfo.Text = "Invalid username or password.";
}
}
It is the login code on every page,
<%
string url = "~/Login.aspx", text = "Log in";
if (Convert.ToBoolean(Session["sIsAuthenticated"] ?? false))
{ url = "~/Home.aspx"; text = "Log out"; }
%>
<%: text %>
</div>

Object reference not set to an instance of an object while clicking on submit button

I have created a webpage in asp.net
on right hand side I have an ListBox which binds data from database when page loads, Its code at Default.aspx is as below
<asp:ListBox ID="ListOfSql" runat="server"
SelectionMode="Single" DataTextField="sql_name" DataValueField="sql_text"
style="margin-left: 0px; width:auto; height:300px" EnableViewState="true">
</asp:ListBox>
and at default.aspx.cs page its code is
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
I am calling loadSqlList() on page_load so that I can get list from database in ListBox.
Now I have an submit button
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
on default.aspx.cs page submit button's code is
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
Now when I want that on clicking on submit button then text of selected item should appear in textbox which is at left hand side
when I do so I am getting an error page
complete code of default.aspx.cs page is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
System.Data.OracleClient.OracleConnection conn = new OracleConnection("Data Source = orcl; user id=*****;password = *****; unicode = true;");
//OracleConnection conn = new OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=system;password = ravi_123;Unicode=True");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
loadSqlList();
lblLastRefresh.Text = DateTime.Now.ToShortTimeString();
lblDate.Text = DateTime.Now.ToShortDateString();
Response.Cache.SetAllowResponseInBrowserHistory(false);
//============================================= Checking user logged in or not ===================================
//if (Session["txtUserName"] == null)
//{
// Response.Write("<Script Language ='JavaScript'> alert('Session Expired, please login again')</script>");
// conn.Close();
// Response.Redirect("login.aspx");
//}
//============================================= Checking user logged in or not (END) ===================================
//=====================User Ip Tracer =======================
string UserIp = Request.ServerVariables["http_x_forwarded_for"];
string UserHost = Request.ServerVariables["http_X_forwarded_for"];
string userMacAdd = Request.ServerVariables["http_x_forwarde_for"];
if (string.IsNullOrEmpty(UserIp))
{
UserIp = Request.ServerVariables["Remote_ADDR"];
UserHost = System.Net.Dns.GetHostName();
}
LblLoc.Text = UserIp;
LblHostName.Text = UserHost;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.AddHeader("Pragma", "no-cache");
//=====================User Ip Tracer code end =======================
if (!IsPostBack)
{
}
}
protected void onclick_logout(object sender, EventArgs e)
{
conn.Close();
Session.Clear();
Response.Redirect("login.aspx");
}
protected void exportToExcel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql;
sql = txtQuery.Text.ToString();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
//================ User Details Data Insertion in DataBase Ends here ===============
da.Fill(dt);
ExportTableData(dt);
Response.Write("<Script>alert('Ip Locked in DB')</Script>");
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void btnClear_clik(object sender, EventArgs e)
{
txtQuery.Text = string.Empty;
}
private void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename="+ListOfSql.SelectedItem.Text.ToString()+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
// References for this page
// http://forums.asp.net/t/1768549.aspx
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
}
If a selection isn't made then ListOfSql.SelectedItem will be null, and therefore calling .Text on that will result in your error.
Try changing your code to something like this:
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
if(ListOfSql.SelectedItem != null)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
}

how to map a checkbox to update the database after submit.

I need to use a the session dataTable email value for the #email and the base from the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
string str;
protected void Submit_Click(object sender, EventArgs e)
{
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + "x";
}
}
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set Question1 = #str WHERE email = #email AND Base = #base;";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#email", Session.dt.email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#base", DropDownList1.base);
}
}
Your syntax for reading the value out of Session is wrong, you cannot use Session.dt.email.
You need to read the DataTable out of Session and cast it to a DataTable, like this:
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
email = dataTable.Rows[0]["Email"].ToString();
}
Now you can use the email string value in your SQL command parameters, like this:
cmd.Parameters.AddWithValue("#email", email);
UPDATE:
You will want to wrap your drop down list binding in Page_Load with a check for IsPostBack, because as your code is posted it will bind the drop down list every time the page loads, not just the first time, thus destroying whatever selection the user made.
Instead do this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
}
Now your base value in your database parameter logic should be the value the user selected.

[System.NullReferenceException: Object reference not set to an instance of an object.]

I am trying to select a user from my default_information.aspx.cs page and display that user information on my registration.aspx page where I already created a registration form.
I am getting System.NullReferenceException:Object reference not set to an instance of an object error. Please help me. I've given the main part of it. I debugged it. I found every data is selected from my DB in string strusername,strpassword. But code breaks on usernametxt.Text = strusername; when i try to show username or password on that text field.
default_information contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{
registration objdef = new registration();
string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
objdef.displayuser(username);
}
protected void update_Click(object sender, EventArgs e)
{
Response.Redirect("registration.aspx");
}
registration.aspx contains
protected void register_Click(object sender, EventArgs e)
{
user objuser = new user();
objuser.username = usernametxt.Text;
objuser.password = passwordtxt.Text;
objuser.email = emailtxt.Text;
objuser.Save();
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
user class contains
public class user
{
public void Save()
{
clssqlserver obj = new clssqlserver();
obj.insertuser_info(Username,Password,Email);
}
public DataSet profile(string username)
{
clssqlserver obj = new clssqlserver();
return obj.getalluser_info(username);
}
}
clssqlserver contains
public DataSet getalluser_info(string username)
{
string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string command = "Select * from login_donor where username='" + username + "' ";
SqlCommand objcommand = new SqlCommand(command, objconnection);
DataSet objdataset = new DataSet();
SqlDataAdapter objadapter = new SqlDataAdapter(objcommand);
objadapter.Fill(objdataset);
objconnection.Close();
return objdataset;
}
public bool insertuser_info(string username,string password,string email)
{ string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string strInsertCommand = "insert into login_donor values('"+ username +"','"+ password + "','"+email+"')";
SqlCommand objcommand = new SqlCommand(strInsertCommand, objconnection);
objcommand.ExecuteNonQuery();
objconnection.Close();
return true;
}
It looks like you are using the asp.net create user wizard control.Because your controls are buried inside another container, you have to be rewarded after some little excavation..Lets start digging......
Using the wizard which is already accessible locate your text box
TextBox usernametxt= (TextBox)CreateUserWizard.FindControl("usernametxt");
usernametxt.Text = strusername;
Hope this will help.
You should check this line
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
you are trying to access directly objDataset.Tables[0], what if there is no user with the supplied username to this method getalluser_info(string username), will the dataset fill the table.
you should first check whether there is any table in the dataset or not.
hope this helps
well i ve found the solution...i was passing Data Between Webforms in worng way..here is the link which helps me: http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
here is the solution
default_information.aspx contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{ string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
Response.Redirect("registration.aspx?id="+username);
}
registration.aspx contains:
protected void Page_Load(object sender, EventArgs e)
{
string queryStringID = Request.QueryString["id"];
displayuser(queryStringID);
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}

How to get modified value of TextBox

This is PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
}
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
I have get value of QueryString from another page and file my fields according to File variable fetching data from database corresponding to File data .Fields(Two Textbox and two DropDwnList) are filling correctly but when i modify data in textbox or DDL and Click on Update button then it is not updating data .
Update Button code
protected void BtnUpdate_Click(object sender, EventArgs e)
{
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("UPDATE_DATA",Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE_NO", TxtFile.Text);
com.Parameters.AddWithValue("#SUB",TxtSub.Text);
com.Parameters.AddWithValue("#UNIT",DDL_U.SelectedValue);
com.Parameters.AddWithValue("#BRANCH",DDL_Branch.SelectedValue);
com.ExecuteNonQuery();
Label1.Text = "Action perfomed successfully !!!";
Bussiness_logic.CloseConnection();
Bussiness_logic.Empty_Control(TxtFile, TxtSub, DDL_U, DDL_Branch);
//GridView1.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
}
Put Your second if also in first if.Because when you click update button than your page load event fire first.Means your textbox value again set from textbox.So putting your second if inside first if stop setting the textbox value from database on postbask,

Resources