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>();
}
Related
I have wrote an application which is connected to an SQL server. There is a function which list out one of the table's rows in a DataGridView. This DataGridView is bound to a BindingSource which is connected to the table directly via a DataSet. It has been clicked via GUI.
My problem is, when something changes in the table, the DataSource is not refreshing. Not even I edit something via my application or just delete a row it still stands there even if the SQL table does not contains anymore.
I have wrote a refresh procedure which have been called every time I click on the table view menu or use the refresh button, it looks like that:
public void SrvMgmtRefresh()
{
string select = "select * from ServersInput";
srvMgmtDataGridView.DataSource = null;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(select, con);
DataSet DS = new DataSet();
sqlDataAdapter.Fill(DS, "ServersInput");
srvMgmtDataGridView.DataSource = DS.Tables[0];
}
Does anyone have any idea what I have did wrong? I see in the application that it reload the content of the table but it still not refresh.
Thanks in advance.
Try this :
DataSet ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter("ProcedureName", _context.Database.GetConnectionString()))
{
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add(new
SqlParameter("#isMedicationPerscriber", SqlDbType.Bit)).Value =
filteringParams.IsMedicationPerscriber;
sda.SelectCommand.Parameters.Add(new
SqlParameter("#isInpersonSession", SqlDbType.Bit)).Value =
filteringParams.InpersonSession;
sda.Fill(ds);
}
int totalRecords = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
var items = ds.Tables[0].AsEnumerable()
.Select(dataRow => new User
{
ZipCode = dataRow.Field<string>("ZipCode"),
IsDeleted = dataRow.Field<bool>("IsDeleted"),
IsConnected = dataRow.Field<bool>("IsConnected"),
Latitude = dataRow.Field<double?>("Latitude"),
Longitude = dataRow.Field<double?>("Longitude"),
}).Where(x => x.UserId != Guid.Parse(filteringParams.UserId)).ToList();
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;
I am trying to insert categories and subcategories from Excel into a database table.
I have 1 Excel file which contains some data and from this Excel file I am creating dataset which contains lots of datatables.
In this dataset I have 2 datatables in the form of this:
Datatable 0 with records:Category
ParentCategory Description
Electronics jhdkhsd
Sports kjshfhs
Datatable 1 with records:SubCategory
Subcategory ParentCategory Description
Mobile Electronics weprwp
Tv Electronics sdflskd
Balls Sports kjshdfkjh
Shoes Sports uytuyt
Now my database tables are like this:
Category:Id,Name,Description,parentid
So far I am successful inserting parent category but now trying to insert child categories but that is where currently i am struggling.
This my code so far:
var dsFinal = new DataSet();
//Some code to read excel sheets and data from excel and create datatables and records with it.
dsControlSheet.Tables[0].Columns.Add("Id");
DataColumn parentId = new DataColumn("ParentId", typeof(int));
parentId.DefaultValue = 0;
dsFinal.Tables[0].Columns.Add(parentId);
dsFinal.Relations.Add("Abc",dsFinal.Tables[0].Columns["ParentCategory"],
dsFinal.Tables[1].Columns["ParentCategory"],false); //creating relation ship between Category datatable
// and SubCategory datatable on field ParentCategory
using (SqlConnection connection = new SqlConnection(""))
{
SqlDataAdapter adapter = new SqlDataAdapter();
var insertCommand = new SqlCommand("insert into Category (Name,Description) values (#ParentCategory,#Description) SET #Id = SCOPE_IDENTITY()", connection);
var parameter = insertCommand.Parameters.Add("#Id", SqlDbType.Int, 0, "Id");
insertCommand.Parameters.Add("#ParentCategory", SqlDbType.NVarChar, 50, "ParentCategory");
insertCommand.Parameters.Add("#Description", SqlDbType.NVarChar, 50, "Description");
parameter.Direction = ParameterDirection.Output;
insertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
adapter.InsertCommand = insertCommand;
adapter.Update(dsFinal.Tables[0]); //successfully inserted parent category and got autoincremented value in Id column of my 0th datatable
//trying to insert child category using above insert command
foreach (DataRow parentCategory in dsFinal.Tables[0].Rows)
{
var child = parentCategory.GetChildRows("Abc").CopyToDataTable();//get child category of particular parent
adapter.Update(child);
}
}
Here in the last loop to insert child category; I am confused about how to use
same insertCommand variable to insert child category?
Update:I have used datatable Expression to calculate parentid like this:
using (SqlConnection connection = new SqlConnection(""))
{
SqlDataAdapter adapter = new SqlDataAdapter();
var insertCommand = new SqlCommand("insert into Category (Name,Description) values (#ParentCategory,#Description) SET #Id = SCOPE_IDENTITY()", connection);
var parameter = insertCommand.Parameters.Add("#Id", SqlDbType.Int, 0, "Id");
insertCommand.Parameters.Add("#ParentCategory", SqlDbType.NVarChar, 50, "ParentCategory");
insertCommand.Parameters.Add("#Description", SqlDbType.NVarChar, 50, "Description");
parameter.Direction = ParameterDirection.Output;
insertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
adapter.InsertCommand = insertCommand;
adapter.Update(dsFinal.Tables[0]); //successfully inserted parent category and got autoincremented value in Id column of my 0th datatable
//For inserting child category..
//added column parentid to store child category
SqlDataAdapter da = new SqlDataAdapter();
dsFinal.Tables[1].Columns.Add("ParentId", typeof(int), "IIF(Parent.ParentCategory=ParentCategory,parent.Id,0)");
var insertChildCategoryCommand = new SqlCommand("insert into Category (Name,Description,ParentId) values (#Subcategory,#Description,#ParentId) SET #Id = SCOPE_IDENTITY()", connection);
var parameter1 = insertChildCategoryCommand.Parameters.Add("#Id", SqlDbType.Int, 0, "Id");
insertChildCategoryCommand.Parameters.Add("#Subcategory", SqlDbType.NVarChar, 50, "Subcategory");
insertChildCategoryCommand.Parameters.Add("#Description", SqlDbType.NVarChar, 50, "Description");
insertChildCategoryCommand.Parameters.Add("#ParentId", SqlDbType.int, 0, "ParentId");
parameter1.Direction = ParameterDirection.Output;
insertChildCategoryCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
da.InsertCommand = insertChildCategoryCommand;
//Error here that computed column cannot be inserted.Here computed column is parentid
da.Update(dsFinal.Tables[1]);
}
Error:Computed column(parentid) cannot be inserted.
You are almost there with latest code.
The only problem is that the calculated columns are not allowed to be used for inserting/updating the database table. Btw, the error message is not "Computed column(parentid) cannot be inserted.", but:
The column mapping from SourceColumn 'ParentId' failed because the DataColumn 'ParentId' is a computed column.
I could agree that the message could have been better, and also I didn't find any documentation describing that. Most probably the rationale is that the computed columns are not normally stored.
Whatever the reason is, that's the reality. You have no other choice than creating a regular column and populating it with data manually.
There are many ways to do that (both efficient and ineffient), but once you already created a relation, you can use the DataRow.GetParentRow method to locate the related category record.
With all that being said, replace the line
dsFinal.Tables[1].Columns.Add("ParentId", typeof(int),
"IIF(Parent.ParentCategory=ParentCategory,parent.Id,0)");
with the following snippet:
var dtSubCategory = dsFinal.Tables[1];
dtSubCategory.Columns.Add("ParentId", typeof(int));
foreach (var drSubCategory in dtSubCategory.AsEnumerable())
{
var drCategory = drSubCategory.GetParentRow("Abc");
drSubCategory["ParentId"] = drCategory != null ? drCategory["Id"] : 0;
}
and you are done.
EDIT: Let me make it clear. The only time critical operation here is locating the category id by name. Using the relation and GetParentRow is equivalent of the evaluating the expression accessing parent as in your attempt. Data relation internally maintains a lookup structure for supporting such operations.
If you want to get the best possible performance, then don't create a relation, but a dictionary. What you need is given a name (string), find the corresponding id (int), so Dictionary<string, int> is a perfect candidate for that:
var categoryIds = dsFinal.Tables[0].AsEnumerable().ToDictionary(
dr => dr.Field<string>("ParentCategory"), // key
dr => dr.Field<int>("Id") // value
);
var dtSubCategory = dsFinal.Tables[1];
dtSubCategory.Columns.Add("ParentId", typeof(int));
foreach (var drSubCategory in dtSubCategory.AsEnumerable())
{
int categoryId;
categoryIds.TryGetValue(drSubCategory.Field<string>("ParentCategory"), out categoryId);
drSubCategory["ParentId"] = categoryId;
}
Change your relation so it's using Id and ParentId and your first solution will be working just right.
When you will update that first table and the get the autoincremented value, it will automatically update the second table via the relation. Here is an example.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
var colParent = dt.Columns.Add("id", typeof(int));
DataTable dtChild = new DataTable();
var colChild = dtChild.Columns.Add("parentid", typeof(int));
ds.Tables.Add(dt);
ds.Tables.Add(dtChild);
ds.Relations.Add("relation1", colParent, colChild);
DataRow rowParent = dt.NewRow();
rowParent["id"] = 1;
dt.Rows.Add(rowParent);
DataRow rowChild = dtChild.NewRow();
rowChild["parentid"] = rowParent["id"];
dtChild.Rows.Add(rowChild);
// at this point, parentid from rowChild is "1".
rowParent["id"] = 10; // DataAdapter.Update simulation.
// and now parentid from rowChild has been update via the relation to "10".
When using this method, i'll usually set my column to get a temporary "id" value by setting the column as an identity column with a seed and step set to -1. This would go after the third line.
colParent.AutoIncrement = true;
colParent.AutoIncrementSeed = -1;
colParent.AutoIncrementStep = -1;
Unless you really need to have your relation on those string fields, there's no need to do any loop, computed column or anything overly complicated.
I'm looking at the example here:
http://msdn.microsoft.com/en-US/library/y06xa2h1(v=vs.80).aspx
string s = "primaryKeyValue";
DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s);
if (foundRow != null)
{
MessageBox.Show(foundRow[1].ToString());
}
else
{
MessageBox.Show("A row with the primary key of " + s + " could not be found");
}
They don't specify where does dataSet1 come from and does this represent some database?
I'm trying to use this example in my code to find unique rows but I can't seem to implement this syntax. I'm only using connection string to open connection to SQL and I use SqlDataAdapter to perform functions...
EDIT:
SqlConnection myConnection = new SqlConnection("Data Source=server; Initial Catalog=Dashboard; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
SqlDataAdapter da = new SqlDataAdapter();
try
{
//Opens the connection to the specified database
myConnection.Open();
//Specifies where the Table in the database where the data will be entered and the columns used
da.InsertCommand = new SqlCommand("INSERT INTO DashboardLibAnswer(Id,Date,Time,Question,Details,Answer,Notes,EnteredBy,WhereReceived,QuestionType,AnswerMethod,TransactionDuration)"
+ "VALUES(#Id,#Date,#Time,#Question,#Details,#Answer,#Notes,#EnteredBy,#WhereReceived,#QuestionType,#AnswerMethod,#TransactionDuration)", myConnection);
//Specifies the columns and their variable type where the data will be entered
//Special note: Conversion from String > DateTime will cause exceptions that will only import some part of data and not everything
da.InsertCommand.Parameters.Add("#Id", SqlDbType.NVarChar);
da.InsertCommand.Parameters.Add("#Date", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#Time", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#Question", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#Details", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#Answer", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#Notes", SqlDbType.Text);
da.InsertCommand.Parameters.Add("#EnteredBy", SqlDbType.NVarChar);
da.InsertCommand.Parameters.Add("#WhereReceived", SqlDbType.NVarChar);
da.InsertCommand.Parameters.Add("#QuestionType", SqlDbType.NVarChar);
da.InsertCommand.Parameters.Add("#AnswerMethod", SqlDbType.NVarChar);
da.InsertCommand.Parameters.Add("#TransactionDuration", SqlDbType.NVarChar);
//Using the global variable counter this loop will go through each valid entry and insert it into the specifed database/table
for (int i = 0; i < counter; i++)
{
//Iterates through the collection array starting at first index and going through until the end
//and inserting each element into our SQL Table
DataSet dashboardDS = new DataSet();
da.Fill(dashboardDS, "DashboardLibAnswer");
DataTable dt = dashboardDS.Tables["DashboardLibAnswer"];
foreach (DataColumn col in dt.Columns)
{
if (col.Unique)
{
da.InsertCommand.Parameters["#Id"].Value = collection.getIdItems(i);
da.InsertCommand.Parameters["#Date"].Value = collection.getDateItems(i);
da.InsertCommand.Parameters["#Time"].Value = collection.getTimeItems(i);
da.InsertCommand.Parameters["#Question"].Value = collection.getQuestionItems(i);
da.InsertCommand.Parameters["#Details"].Value = collection.getDetailsItems(i);
da.InsertCommand.Parameters["#Answer"].Value = collection.getAnswerItems(i);
da.InsertCommand.Parameters["#Notes"].Value = collection.getNotesItems(i);
da.InsertCommand.Parameters["#EnteredBy"].Value = collection.getEnteredByItems(i);
da.InsertCommand.Parameters["#WhereReceived"].Value = collection.getWhereItems(i);
da.InsertCommand.Parameters["#QuestionType"].Value = collection.getQuestionTypeItems(i);
da.InsertCommand.Parameters["#AnswerMethod"].Value = collection.getAnswerMethodItems(i);
da.InsertCommand.Parameters["#TransactionDuration"].Value = collection.getTransactionItems(i);
da.InsertCommand.ExecuteNonQuery();
}
}
//Updates the progress bar using the i in addition to 1
_worker.ReportProgress(i + 1);
} // end for
//Once the importing is done it will show the appropriate message
MessageBox.Show("Finished Importing");
} // end try
catch (Exception exceptionError)
{
//To show exceptions thrown just uncomment bellow line
//rtbOutput.AppendText(exceptionError.ToString);
} // end catch
//Closes the SQL connection after importing is done
myConnection.Close();
}
if you populate a dataset from your data adapter, you'll be able to follow the same logic -
http://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.71).aspx
It might be worth showing what you actually have to get more specific help
EDIT
I think I'm understanding what you want - if you fill your datatable from the already populated table, just check the item doesn't already exist before adding it - i.e.
if (dt.Rows.Find(collection.getIdItems(i)) == null)
{
// add your new row
}
(just to be sure I knocked together a quick test - hopefully this helps):
// MyContacts db has a table Person with primary key (ID) - 3 rows - IDs 4,5,6
SqlConnection myConnection = new SqlConnection("Data Source=.; Initial Catalog=MyContacts; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Person", myConnection);
myConnection.Open();
DataSet dashboardDS = new DataSet();
da.Fill(dashboardDS, "Person");
dashboardDS.Tables[0].PrimaryKey = new[] { dashboardDS.Tables[0].Columns["ID"]};
List<int> ids = new List<int> {4, 6, 7};
foreach (var id in ids)
{
if (dashboardDS.Tables[0].Rows.Find(id) == null)
{
Console.WriteLine("id not in database {0}", id); //i.e. 7
}
}
You will first need to open a connection to your database. This is an excellent source for connection strings: The Connection String Reference.
Then you will need to fill the dataset with data from some table. Since we are only interested in the schema information we are only selecting one row (SELECT TOP 1 ...).
Then we can go through the columns and check their Unique property (Boolean):
string connString =
"server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = #"SELECT TOP 1 * FROM AnyTable";
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
using (DataSet ds = new DataSet()) {
da.Fill(ds, "AnyTable");
DataTable dt = ds.Tables["AnyTable"];
foreach (DataColumn col in dt.Columns) {
if (col.Unique) {
Console.WriteLine("Column {0} is unique.", col.ColumnName);
}
}
}
}
UPDATE #1
Sorry, I missunderstood your question. The above example returns unique columns, not unique rows. You can get unique (distinct) rows by using the DISTINCT keyword in SQL:
SELECT DISTINCT field1, field2, field3 FROM AnyTable
You can then fill the data table the same way as above.
Usually the word "unique" is used for unique constraints and unique indexes in database jargon. The term "distinct" is used for rows which are different.
UPDATE #2
Your updated question seems to suggest that you don't want find unique rows, but that you want to insert unique rows (which is the exact opposite).
Usually you would select distinct items from a collection like this. However it is difficult to answer your question accurately, since we don't know the type of your collection.
foreach (var item in collection.Distinct()) {
}
UPDATE #3
The easiest way to insert distinct values in the SQL Server table is to filter the rows at their origin, when reading them from the CSV-File; even before splitting them.
string[] lines = File.ReadAllLines(#"C:\Data\MyData.csv");
string[][] splittedLines = lines
.Distinct()
.Select(s => s.Split(','))
.ToArray();
Now you have distinct (unique) splitted lines that you can insert into the SQL Server table.
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