I'm creating a WPF application were-in a user creates an account and can log-in with their username and password. When the user successfully logs in their Username and other details that they entered whiles signing up should be displayed on the next page. So far when I do it the only thing that shows up is the info of the first registered user no matter what Username or Password is used but it should be based on who's logged in.
Better explained, There's User A and User B, when User A logs in his info is displayed, when User B logs in, User A's info is still displayed no matter what, I want the info of User B(and all subsequent Users) to show when his specific Username is entered.
C# for Sign Up Command
private void SubmitBtn_Click(object sender, RoutedEventArgs e)
{
if (tbStudentName.Text == "" || pbPassword.Password == "" || tbSchoolName.Text == "" || tbHouseName.Text == ""
|| tbProg.Text == "" || tbPhoneNumber.Text == "" || tbAddress.Text == "")
{
var dim = new Dim();
dim.Show();
this.Effect = new BlurEffect();
var cmb = new Custom_MessageBoxes.CustomMsgBox2();
cmb.ShowDialog();
this.Effect = null;
dim.Close();
}
else
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string InsertUser = "INSERT INTO tblSignUp values ('"+tbStudentName.Text+ "', '" + tbSchoolName.Text + "', '" + tbHouseName.Text + "', '" + tbProg.Text + "', '" + tbPhoneNumber.Text + "', '" + tbAddress.Text + "', '" + pbPassword.Password + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = InsertUser;
obj.cmd.ExecuteNonQuery();
obj.conn.Close();
var dim = new Dim();
dim.Show();
this.Effect = new BlurEffect();
var cmb = new Custom_MessageBoxes.RegistrationComplete();
cmb.ShowDialog();
this.Effect = null;
dim.Close();
Clear();
}
}
C# for Sign In Command
//Sign In button click event
private void UserSignInBtn_Click(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(connectionString);
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM tblSignUp WHERE StudentName = '"+tbID.Text+"' AND Password = '"+PB.Password+"'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
// Custom Message Box and Dim Effect
var jim = new Dim();
jim.Show();
this.Effect = new BlurEffect();
var lsmb = new Custom_MessageBoxes.LoginSuccessfulMsgBox();
lsmb.ShowDialog();
this.Effect = null;
jim.Close();
var User_Homepage = new User_Homepage();
NavigationService.Navigate(User_Homepage);
}
else
{
// Custom Message Box and Dim Effect 2
var him = new Dim();
him.Show();
this.Effect = new BlurEffect();
var rmdlgb = new ReturnMessageDialogueBox();
rmdlgb.ShowDialog();
this.Effect = null;
him.Close();
}
obj.conn.Close();
}
catch(Exception ex)
{
using (EventLog eventlog = new EventLog("Application"))
{
eventlog.Source = "SQL Error: From My Application";
eventlog.WriteEntry(ex.StackTrace, EventLogEntryType.Error, 101, 1);
}
}
finally
{
sqlCon.Close();
}
}
Page where I want user info
string connectionString = #"Data Source=HP;Initial Catalog=User_SignUpDB;Integrated Security=True;";
public UHP()
{
InitializeComponent();
Page1 p1 = new Page1();
var pls = p1.tbID.Text;
SqlConnection sqlCon = new SqlConnection(connectionString);
sqlCon.Open();
string query = "SELECT * FROM tblSignUP WHERE StudentName = StudentName and HouseName = HouseName";
SqlCommand createCommand = new SqlCommand(query, sqlCon);
SqlDataReader dr = createCommand.ExecuteReader();
if (dr.Read())
{
nameTxt.Text = (dr["StudentName"].ToString());
hseTxt.Text = (dr["HouseName"].ToString());
progTxt.Text = (dr["Prog"].ToString());
}
sqlCon.Close();
}
Your query:
SELECT *
FROM tblSignUP
WHERE
StudentName = StudentName
AND HouseName = HouseName
There are no parameters being passed into this; it is just a hardcoded statement.
You're comparing equivalent fields in your WHERE clause, which makes it redundant, i.e. you're really just doing a SELECT * from the table. What you're reading into your application is therefore always just the first row returned.
What you need is something like:
string query = "SELECT * FROM tblSignUP WHERE StudentName = #StudentName and HouseName = #HouseName";
SqlCommand createCommand = new SqlCommand(query, sqlCon);
createCommand.Parameters.Add(new SqlParameter("#StudentName", StudentName));
createCommand.Parameters.Add(new SqlParameter("#HouseName", HouseName));
The variables for StudentName and HouseName that are passed into the SqlParameter constructor (second argument), I'm assuming are already defined in your code somewhere.
Related
How to Display the User Id in my Homepage in ASP MVC. I don't know what is the problem. May I know what are the cause the userId
This is the part of Dashboard
protected void Page_Load(object sender, EventArgs e)
{
string sUserInfo = System.Environment.UserName;
string constr = "Data Source=MyDatabase;Database=test;User Id=username;Password=add3" ;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select SystemName from tbl_SYS_Users where UserId='" + sUserInfo + "'");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
string tempa = "";
while (sdr.Read())
{
tempa += sdr["SystemName"].ToString();
}
lblUserID.Text = Utilities.GetUserInfo(tempa);
}
This is for the Utilities in AppData Folder
public static string GetUserInfo(string sSystem)
{
sSystem = sSystem.ToUpper();
string sUserInfo = System.Environment.UserName;
if (SetConfigs()) //Check config file first
{
//Get userinfo from db server
if (sSystem != "HOME")
{
string sQry = "Select * from tbl_SYS_Users where SystemName = '" + sSystem + "' AND UserId='" + sUserInfo + "'";
using (DataTable dsTable = SQL_Query(Globals.sSQLCS_FNS, sQry, true, false))
{
if (dsTable == null)
{
sUserInfo += " - Unknown User!a";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
if (dsTable.Rows.Count == 0) //ID not found!
{
sUserInfo += " - Unknown User!";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
sUserInfo += " - " + dsTable.Rows[0]["Username"];
Globals.UserID = dsTable.Rows[0]["UserId"].ToString().Trim();
Globals.UserName = dsTable.Rows[0]["Username"].ToString().Trim();
}
}
}
}
}
else if (sSystem != "HOME")
sUserInfo += " - Unknown User!s";
return sUserInfo; // return to lblUserID.Text in the homepage
}
This image is the homepage
This is the database
I Want to display the Username in my Homepage
inject usermanager in to the view and add this
#UserManager.GetUserAsync(User).Result.UserName
What is the scope of Globals class? It seems when page loads class object initialized and all becomes empty. Declare Globals class as static (If not).
I am trying to do lock user account for Invalid login attempts in Asp.Net C# by using Visual Studio 2019. Database is using MySql Workbench 8.0 CE. But facing the error
C# code shown as below:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Canteen_UAT
{
public partial class LoginDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlConnection scon = new MySqlConnection("server = XXX.XXX.XX.XXX; user id = root; password = XXXXX; persistsecurityinfo = True; database = posdbms_uat");
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
String status;
//String lockstatus;
int attemptcount = 0;
if (ds.Tables[0].Rows.Count > 0)
{
uname = ds.Tables[0].Rows[0]["username"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
status = ds.Tables[0].Rows[0]["status"].ToString();
scon.Close();
if (status == "Open")
{
if (uname == TextBox1.Text && pass == TextBox2.Text)
{
Session["username"] = uname;
Response.Redirect("Order.aspx");
}
else
{
Label2.Text = "Invalid Username or Password - Relogin with Correct Username & Password. No of Attempts Remaining : " + (2 - attemptcount);
attemptcount = attemptcount + 1;
}
}
else if (status == "Locked")
{
Label2.Text = "Your Account Locked Already : Contact Administrator";
}
else
{
Label2.Text = "Invalid Username or Password - Relogin wit Correct Username and Password.";
}
if (attemptcount == 3)
{
Label2.Text = "Your Account Has Been Locked Due to Three Invalid Attempts - Contact Administrator.";
setlockstatus(TextBox1.Text);
attemptcount = 0;
}
}
}
private void setlockstatus(String username1)
{
String mycon = "server = xxx; user id = root; password = xxx; persistsecurityinfo = True; database = posdbms_uat";
String updatedata = "Update posdbms_uat.logindetail set status='Locked' where username='" + username1 + "' ";
MySqlConnection con = new MySqlConnection(mycon);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
}
Not sure what might be causing this.
What I have tried:
I created a table as posdbms_uat, datatable match the column name in the database table and with appropriate datatype. Not sure how this error pops up.
The query:
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
...only returns the number of rows matching the WHERE condition - not the actual data in the rows. It should be fixed by specifying the columns you want to get:
String myquery = "select username, password, status from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
Also, you should consider using parametrization to avoid SQL injection (see this SO question). Another thing is, please do not store the password in plain text.
I want to retrieve date and time according to login user in my ASP.NET web application using C#. The code I'm using is just returning the 1st row details.
I want date and time of current login user and bind it to with a label.
I have a table called Userdatatext with 3 columns:
UserName, UserText, LastEditTime
Sorry for my bad English.
Thanks in advance :)
My C# code
protected void Page_Load(object sender,EventArgs e)
{
if (Session["userName"] != null && Session["userName"] != "")
{
LblUser.Text = "Welcome " + Session["userName"].ToString() + "";
}
else
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["DbLogns"].ToString();
SqlConnection objConection = new SqlConnection(Connectionstring);
objConection.Open();
SqlCommand objCommand = new SqlCommand("select LastEditTime from Userdatatext where UserName='" + Session["userName"] + "'", objConection);
DataSet objDataset = new DataSet();
SqlDataAdapter objAdapter = new SqlDataAdapter(objCommand);
objAdapter.Fill(objDataset);
string lastdatetime = objDataset.Tables[0].Rows[0][0].ToString();
Lbllastedit.Text = "Last edit on :-" + lastdatetime;
Lbllastedit.Font.Size = 15;
objConection.Close();
}
catch(IndexOutOfRangeException n)
{
Lbllastedit.Text = "Last edit :- no data found !";
Lbllastedit.Font.Size = 13;
}
}
Try this code with a SqlDataReader:
try
{
string lastdatetime = null;
string Connectionstring = ConfigurationManager.ConnectionStrings["DbLogns"].ToString();
SqlConnection objConection = new SqlConnection(Connectionstring);
objConection.Open();
SqlCommand objCommand = new SqlCommand("select LastEditTime from Userdatatext where UserName='" + Session["userName"] + "'", objConection);
SqlDataReader dr = objCommand.ExecuteReader();
if (dr.Read())
{
lastdatetime = dr["LastEditTime"].ToString();
}
dr.Close();
Lbllastedit.Text = "Last edit on :-" + lastdatetime;
Lbllastedit.Font.Size = 15;
objConection.Close();
}
My C# desktop application has a form ItemsBrowser. My application is about an Inventory system. The ItemsBrowser form loads the Items Details while user add a new sale or new purchase. Here is LoadAllItems() code: -
void LoadAllItems()
{
DBConnector dbc = new DBConnector();
AccountsBasic.Classes.DBConnector dbca = new AccountsBasic.Classes.DBConnector();
ArrayList lstItems = dbc.GetAllItems();
var AddedItems = new List<DataGridViewRow>();
Cursor.Current = Cursors.WaitCursor;
dgvItems.Rows.Clear();
for (int i=0; i<=lstItems.Count-1; i++)
{
Item itm = (Item)lstItems[i];
ItemCategory ItemCat = dbc.GetThisItemCategory(itm.ItemCategoryCode);
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvItems);
row.Cells[0].Value = dbca.GetThisParty(dbc.GetThisItemCategory(itm.ItemCategoryCode).SupplierCode).PartyName;
row.Cells[1].Value = ItemCat.ItemCategoryName;
row.Cells[2].Value = itm.ItemID.ToString();
row.Cells[3].Value = itm.ItemName;
row.Cells[4].Value = itm.RetailPrice.ToString();
row.Cells[5].Value = dbc.GetPresentStock_By_ItemID(itm.ItemID).ToString();
AddedItems.Add(row);
//dgvItems.Rows.Add(dbca.GetThisParty(dbc.GetThisItemCategory(itm.ItemCategoryCode).SupplierCode).PartyName, dbc.GetThisItemCategory(itm.ItemCategoryCode).ItemCategoryName, itm.ItemID.ToString(), itm.ItemName, itm.RetailPrice, dbc.GetPresentStock_By_ItemID(itm.ItemID).ToString());
}
dgvItems.Rows.AddRange(AddedItems.ToArray());
dgvItems.AutoResizeColumns();
Cursor.Current = Cursors.Default;
}
This function was working fine and in speed. But suddenly It got slow very much. By checking each line one by one in the loop, I found that when a statement accessing the database like
ItemCategory ItemCat = dbc.GetThisItemCategory(itm.ItemCategoryCode);
the database access gets very slow. Although it was running pretty fine before. There are total 955 items in the table.
ALSO A VERY STRANGE THING I HAVE NOTICED...
I have installed this application on the client's machine and it is working fine there on client's machine with no delay...
GetAllItems() Function
public ArrayList GetAllItems(string SupplierCode = "", string ItemCategory = "")
{
if (SupplierCode != "" && ItemCategory != "")
comm.CommandText = "SELECT Items.ItemID, Items.ItemName, Items.Description, Items.ItemCategoryCode, Items.OpeningStock, Items.RetailPrice FROM Items, ItemCategories WHERE Items.ItemCategoryCode = ItemCategories.ItemCategoryCode AND ItemCategories.SupplierCode = '" + SupplierCode + "' AND ItemCategories.ItemCategory = '" + ItemCategory + "' ORDER BY Items.ItemID";
else if (SupplierCode != "" && ItemCategory == "")
comm.CommandText = "SELECT Items.ItemID, Items.ItemName, Items.Description, Items.ItemCategoryCode, Items.OpeningStock, Items.RetailPrice FROM Items, ItemCategories WHERE Items.ItemCategoryCode = ItemCategories.ItemCategoryCode AND ItemCategories.SupplierCode = '" + SupplierCode + "' ORDER BY ItemCategories.SupplierCode, ItemCategories.ItemCategory";
else if (SupplierCode == "" && ItemCategory != "")
comm.CommandText = "SELECT Items.ItemID, Items.ItemName, Items.Description, Items.ItemCategoryCode, Items.OpeningStock, Items.RetailPrice FROM Items, ItemCategories WHERE Items.ItemCategoryCode = ItemCategories.ItemCategoryCode AND ItemCategories.ItemCategory = '" + ItemCategory + "' ORDER BY Items.ItemID";
else
comm.CommandText = "SELECT * FROM Items Order By ItemID";
ArrayList AllItems = new ArrayList();
conn.Open();
SqlDataReader dr;
dr = comm.ExecuteReader();
while (dr.Read())
{
Item it = new Item();
it.ItemID = dr.GetInt32(0);
it.ItemName = dr.GetString(1);
it.Description = dr.IsDBNull(2) ? "" : dr.GetString(2);
it.ItemCategoryCode = dr.IsDBNull(3) ? -1 : dr.GetInt32(3);
it.OpeningStock = dr.IsDBNull(4) ? 0 : dr.GetInt32(4);
it.RetailPrice = dr.IsDBNull(5) ? 0 : dr.GetDouble(5);
AllItems.Add(it);
}
dr.Close();
conn.Close();
return AllItems;
}
GetThisItemCategory() Function
public ItemCategory GetThisItemCategory(int ItemCategoryCode = -1, string SupplierCode = "", string ItemCategory = "")
{
if (ItemCategoryCode == -1 && SupplierCode != "" && ItemCategory != "")
comm.CommandText = "SELECT * FROM ItemCategories WHERE SupplierCode = '" + SupplierCode + "' AND ItemCategory = '" + ItemCategory + "' Order By SupplierCode, ItemCategory";
else if (ItemCategoryCode == -1 && SupplierCode == "" && ItemCategory != "")
comm.CommandText = "SELECT * FROM ItemCategories WHERE ItemCategory = '" + ItemCategory + "' Order By ItemCategory";
else// if (ItemCategoryCode != -1 && SupplierCode == "" && ItemCategory == "")
comm.CommandText = "SELECT * FROM ItemCategories WHERE ItemCategoryCode = '" + ItemCategoryCode + "' Order By SupplierCode, ItemCategory";
SqlDataReader dr;
ItemCategory ic = new ItemCategory();
ic.ItemCategoryCode = -1;
conn.Open();
dr = comm.ExecuteReader();
if (dr.Read())
{
ic.ItemCategoryCode = dr.GetInt32(0);
ic.SupplierCode = dr.GetString(1);
ic.ItemCategoryName = dr.GetString(2);
ic.OrderableStockLimit = (dr.IsDBNull(3)) ? -1 : dr.GetInt32(3);
}
dr.Close();
conn.Close();
return ic;
}
Actually, problem is not about specific function. It is about any database access, whether it is GetThisItemCategory() or GetPresentStock_By_ItemID() function.
PLEASE NOTE EARLIER IT WAS WORKING PRETTY FINE. SUDDENLY IT STARTED BEHAVING IN THIS MANNER...
You need to learn how to do "named parameters", to protect against injected sql attacks AND to get maximum plan-reuse from your RDBMS.
Here is an example:
using System;
using System.Data;
using System.Data.SqlClient;
class ParamDemo
{
static void Main()
{
// conn and reader declared outside try
// block for visibility in finally block
SqlConnection conn = null;
SqlDataReader reader = null;
string inputCity = "London";
try
{
// instantiate and open connection
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// don't ever do this
// SqlCommand cmd = new SqlCommand(
// "select * from Customers where city = '" + inputCity + "'";
// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = #City", conn);
// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#City";
param.Value = inputCity;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
// get data stream
reader = cmd.ExecuteReader();
// write each record
while(reader.Read())
{
Console.WriteLine("{0}, {1}",
reader["CompanyName"],
reader["ContactName"]);
}
}
finally
{
// close reader
if (reader != null)
{
reader.Close();
}
// close connection
if (conn != null)
{
conn.Close();
}
}
}
}
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
You can read a few things about dynamic sql in this article.
http://sqlmag.com/database-performance-tuning/don-t-fear-dynamic-sql
(There is a mini overlap between your .cs C# "inline" sql vs this article...it'll give you a few things to research further if you're inclined)
.....
Finally, you need to learn the basics of "index tuning".
You can get an intro to that here:
https://sqlserverperformance.wordpress.com/2010/04/06/a-dmv-a-day-%E2%80%93-day-7/
As a guess, I would create an index on
ItemCategories.ItemCategoryCode
and a seperate index on
ItemCategories.SupplierCode
APPEND:
Finally, can you try this version of the code?
You want to get-rid of DataReaders as soon as possible, so your connection pool does not run out of connections.
public ItemCategory GetThisItemCategory(int ItemCategoryCode = -1, string SupplierCode = "", string ItemCategory = "")
{
using (SqlCommand cmd = new SqlCommand("MyConnectionString")
{
/* TO DO !!! , build your sql-string and parameter list here */
using (IDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if /*while*/ (dataReader.Read())
{
ic.ItemCategoryCode = dr.GetInt32(0);
ic.SupplierCode = dr.GetString(1);
ic.ItemCategoryName = dr.GetString(2);
ic.OrderableStockLimit = (dr.IsDBNull(3)) ? -1 : dr.GetInt32(3);
}
if (dataReader != null)
{
try
{
dataReader.Close();
}
catch { }
}
}
cmd.Close();
}
return ic;
}
Here is my log in page code. What I want to do is when the user inputs his/her username, it will then get all of the database records "based on that username input" of the customer and store it in a single session.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
I have set the Session["Username"] to the user input(txtUser.text), but what I want to do is to get all of the database records on that username that the customer will enter.
Afterwards, I am planning to call on that specific database record and bind it to the order .aspx page. I have tried this code below but its only showing me the Session["Username"], since I have called it on the login page.
txtCustomerName.Text = Session["Username"].ToString();
txtCustomerPhoneNo.Text = Session["Contact"].ToString();
txtCustomerEmailID.Text = Session["Email"].ToString();
txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
You can create a data structure to store the information you need.
public class Person
{
public string Username { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
using (SqlCommand command = new SqlCommand(
"SELECT * FROM databaseTablename where username = " + txtUser.Text, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Person person = new Person();
person.Username = reader.GetString(reader.GetOrdinal("username"));
person.Contact = reader.GetString(reader.GetOrdinal("contact"));
person.Email = reader.GetString(reader.GetOrdinal("email"));
person.Password = reader.GetString(reader.GetOrdinal("password"));
}
}
}
}
You can then store this object in a session like so:
Session["username"] = person;
Later on, if you want to access the contents of the session, say in the Order.aspx page, you can do like so:
Person person = (Person)Session["username"];
get the records from the database. Store it in a comma separated string.
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
SqlDataAdapter da=new SqlDataAdapter(scm);
DataSet ds=new DataSet();
da.Fill(ds);
conn.Close();
string userdata="";
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
userdata+=","+row[i].ToString();
}
}
userdata=userdata.TrimStart(',');
Session["username"]= userdata;
for getting all the records just get this string from session and split it
If(Session["username"]!=null)
String user=Session["username"].ToString();
string[] udat=user.Split(',');
you can get all data in this string array.
Im kind of new to programming so please excuse any error.
This is for storing your all values in single session
DataBaseConnection db = new DataBaseConnection();
DataTable dt = new DataTable();
dt = db.executeNonQuery("Your Query that retrieves all user's data goes here");
if(dt.Rows.Count > 0)
{
List<string> lst = new List<string>();
foreach(DataRow dr in dt.Rows)
{
lst.Add(dr["Cloumn_1"].ToString());
lst.Add(dr["Column_2"].ToString());
.
.
Session["YourSessionName"] = lst;
}
}
here DataBaseConnection is class that returns connection string of database, so now you know what to do.
i hope this helps. Let me know