Get profile id using username in DB - c#

I have to catch the username entered in the login page and get corresponding profileid(the column in DB) and show it in another page my DAL code is
public DataTable getall()
{
SqlConnection conn1 = Generic.DBConnection.OpenConnection();
DataTable dt=new DataTable();
try
{
string sql = "Select * from Profile_Master";
SqlCommand cmds = new SqlCommand(sql,conn1);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmds);
sqlDa.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
My UI
DataTable dt1 = new DataTable();
ProfileMasterDAL dal = new ProfileMasterDAL();
dt1 = dal.getall();
if (dt1.Rows.Count > 0)
{
Session["sdds"] = dt1.Rows[0]["FirstName"].ToString();
Session["EmailId"] = dt1.Rows[0]["EmailID"].ToString();
Session["pid"] = dt1.Rows[0]["NewidColumn"].ToString();
Response.Redirect("~/Myhome.aspx");
but i am able to get the first value in the DB not the corresponding value for the username?

Your select statement has 10 rows. and the required row for you is in 5th position.
when you say dt1.Rows[0]["FirstName"] you will get only the first record but not the 5th record.
If you want to make this work, add where condition to your select statement, which returns exactly one required row for you.
something like..
"select * from Profile_Master PM Where PM.UserName = #username"
where #username is your input from login page. And is unique in the database Table

Related

Problem with dataset when table does not exist

I get an error when the wrong credential is entered but if I enter a true credential then I do not get an error.
See my login screen: if I enter true credential then I do not get any error
But if I enter the wrong credential then I get an error because the second table does not exist
The error is Cannot find table 1
HomeController.cs
[HttpPost]
public ActionResult ExecutiveLogin(int? exuserid, string exusername)
{
SqlCommand cmd = new SqlCommand("executivelogin", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#executiveid", exuserid);
cmd.Parameters.AddWithValue("#executivetypename", exusername);
cn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
ds.Tables[0].TableName = "Error Message";
ds.Tables[1].TableName = "Customer Data";
var message = ds.Tables[0].Rows[0].ItemArray[0];
//object result = cmd.ExecuteScalar();
List<Customer> query = null;
if (ds.Tables[0].TableName == "Error Message")
{
ViewBag.errormessage = message;
var Customerdata = (from DataRow row in ds.Tables[1].Rows
select new Customer
{
CustomerName = row["CustomerName"].ToString(),
Type = row["type"].ToString(),
});
query = Customerdata.ToList();
ViewBag.custdata = query;
}
else
{
ViewBag.errormessage = message;
}
return View();
}
if I enter a true credential then not give an error and I enter the wrong credential then give an error
If the user exists, you are executing two SELECT statements, so there are two DataTables in your DataSet. If the user doesn't exist, you're only executing one SELECT statement, so there's only one DataTable, so index 1 is out of range. You should be checking the contents of the first DataTable first, to see whether the login was successful, or else just check the number of DataTables first. Only if there is a second DataTable, should you try to get that second DataTable.
Check for the count in dataset, then set name for second table.
ds.Tables.Count > 0 ? ds.Tables[1].TableName = "Customer Data" : /*No second datatable */;

Loop through datatables to find matching values in one column

I have a datatable which currently displays all the records from a database table. I am using asp.net and ado.net. The table is populated by a stored procedure which is simply select * from table. When my view loads the table gets populated with all records. I want the table to display only related records at a time until those records in the table have been authorised (accepted or rejected and then records are inserted to other tables) or a 'Next' button is clicked. These records would be grouped by ID. What ID that shows up first when the view loads just depends on what the first record ID is.
To give an example of data and how I want it displayed:
All records:
PageID AID Name
1 60 Book1
2 60 Book7
3 50 Book7
4 60 Book8
5 70 Book12
6 70 Book7
The first ID is 60(AID) so I would want it to loop through the column, find all that are AID60, display them in the view, once all have been actioned, it would move to AID50 etc etc...
PageID AID Name
1 60 Book1
2 60 Book7
4 60 Book8
What I have currently in the Controller to get the records is:
public ActionResult toAction()
{
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstringpath"].ToString());
List<ActionModel> AList = new List<ActionModel>();
SqlCommand com = new SqlCommand("Action", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
foreach (DataRow dtRow in dt.Rows)
{
string CurrentAID = dtRow["AID"].ToString();
if (dtRow["AID"].ToString().Equals(CurrentAID))
{
AList = (from DataRow dr in dt.Rows
select new ActionModel()
{
PageID = Convert.ToInt32(dr["PageID"]),
AID = Convert.ToInt32(dr["AID"]),
Name = Convert.ToString(dr["Name"])
}).ToList();
}
}
return View(AList);
}
I am aware the the above code is incorrect as the foreach loop does not work. The idea would be to
Get the AID of the first record in the table, loop through the rest of the column looking for the same AID and add all records to the list to display to the view. Once actioned in the view the next AID will populate. (I have the Accept/Reject/Next buttons already)
I just need to get the foreach working correctly to only show out one AID at a time. I will not be passing an AID as a parameter so the likes of Select * from Action where AID = #AID will not work.
public ActionModel toAction()
{
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstringpath"].ToString());
SqlCommand com = new SqlCommand("Action", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
return dt.Select("AID = 60").ToList<ActionModel>();
}

Insert multiple data into two tables and need to insert the last inserted id into another table

I have a form which use two tables to insert the data.
Some column in the form would be like:
scholarship name, course, year
Two tables that are involved are:
scholarshipDetail , scholarshipCourse.
scholarshipDetail table has scholarshipName and year
scholarshipCourse table has scholarshipID, course
scholarshipDetail:
schid schName year
-----------------------------
1 star 2015
2 moon 2016
scholarshipCourse:
schID course
------------------
1 maths
1 english
2 maths
Assuming that the new user wants to add new scholarship which means the id will 3 and it insert into two tables. How do I that? (MANAGED TO INSERT ALR)
NEW ERROR:
EDITED
public DataTable test(string name, string course)
{
string insertsql = "INSERT INTO Table1(schName) OUTPUT INSERTED.addID values (#schName)";
SqlCommand cmd = new SqlCommand(insertsql,conn);
cmd.Parameters.AddWithValue("#schName", name);
conn.Open();
int i = cmd.ExecuteNonQuery();
var table1Id = (int)cmd.ExecuteScalar();
string insertsql1 = "INSERT INTO Table2(ScholarshipID, DiplomaCourse) VALUES (#id, #course)";
SqlCommand cmd2 = new SqlCommand(insertsql1, conn);
cmd2.Parameters.AddWithValue("#id", table1Id);
cmd2.Parameters.AddWithValue("#course", course);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.SelectCommand = cmd2;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
The output in my table is
Table1
schID schname
-------------------
1 jj
2 jj
Table2
TableID schID Course
------------------------------
1 2 Maths
the data is being inserted twice in Table1. why is that so? (SOLVED)
Edited:
Now the problem is, there will be checkboxes which allow the user to choose which course is applicable for the scholarship.
When the user click all checkbox, only the last checkbox will insert into database.
In my codebehind(cs):
protected void Button1_Click(object sender, EventArgs e)
{
// addScholarship[] test = new addScholarship[1];
string course = "";
string Name = schName.Text;
if (DIT.Checked )
{
course = "DIT";
}
if (DFI.Checked)
{
course = "DFI";
}
addScholarship[] insertName = new addScholarship[1];
addScholarship insertedName = new addScholarship(Name,course);
scholarshipBLL obj = new scholarshipBLL();
DataTable dt = obj.test(Name, course);
}
For the latest problem you posted.
You are calling obj.test method only once after all the if blocks.
So the "course" variable will have value from the latest if block where the condition is true.
You need to call DataTable dt = obj.test(Name, course); method in every if block. That means if checkbox is checked you call insert row. If not checked then you don't insert the row.
Following is the code you should put in your button_click.
string course = "";
string Name = schName.Text;
scholarshipBLL obj = new scholarshipBLL();
List<addScholarship> addScholarshipList= new List<addScholarship>();
addScholarship scholarship;
if (DIT.Checked )
{
scholarship = new addScholarship(Name,course);
addScholarshipList.Add(insertedName);
course = "DIT";
DataTable dt = obj.test(Name, course);
}
if (DFI.Checked)
{
scholarship = new addScholarship(Name,course);
addScholarshipList.Add(insertedName);
course = "DFI";
DataTable dt = obj.test(Name, course);
}
You are executing the command twice.
int i = cmd.ExecuteNonQuery();
var table1Id = (int)cmd.ExecuteScalar();
You need to execute only one. I think removing cmd.ExecuteNoteQuery would solve your issue.
BEGIN;
INSERT INTO scholarshipDetail(schid,schName,year) VALUES(3,'sun',2017);
INSERT INTO scholarshipCourse(schID,course) VALUES(LAST_INSERT_ID(),'science');
COMMIT;

Select from dataset where data in dataset matches user input

I am trying to query or match user input against a dataset using a DataTable:
I am populating the dataset from a stored procedure which selects only a single column from a single table: Example: UserID Column. **I am not selecting the entire content of the table.*
public static DataSet LoadProfile()
{
SqlCommand cmdSQL = new SqlCommand("usp_LoadProfile", ConnectDatabase);
cmdSQL.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daSQL = new SqlDataAdapter(cmdSQL);
DataSet ds = new DataSet();
daSQL.Fill(ds);
try
{
ConnectDatabase.Open();
cmdSQL.ExecuteNonQuery();
}
catch(Exception)
{
StatusMsg = ex.Message;
}
finally
{
ConnectDatabase.Close();
cmdSQL.Parameters.Clear();
cmdSQL.Dispose();
}
return ds;
}
I have the following method called in the form load event: I need to populate the dataset on from load.
public static DataTable LoadData()
{
DataSet dsView = new DataSet();
dsView = LoadProfile();
DataTable tblExample = dsView.Tables["Example"];
return tblExample;
}
Finally what I would like to do is match the user entry from the DataTable.
I have this in button event:
DataRow[] results;
results = LoadData().Select(txtExample.Text);
Beyond this point, I could use a for loop but there is only one record for each person.
I am trying to match the user entry with the dataset via the datatable.
The last line should be
DataRow[] results;
results = LoadData().Select("UserID = '" + txtExample.Text +"'");
Supposing that UserID is a field of text type. If instead is of numeric type then remove the quotes
results = LoadData().Select("UserID = " + txtExample.Text);
However I should point that the code in LoadProfile following the daSQL.Fill(ds); call is not needed and you can remove it (just return the DataSet though)
Use the following simple query on dataset:
DataRow[] dRow = dataSetName.Tables[0].Select("fieldToMatch = '" + userInput.ToString() + "' ");

problem with getting data from database

I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....
In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;
It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0
I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}

Categories