Load database data into asp.net page - asp.net

I would like to know how to load data from a database into a asp.net form.
So I use code to get the data via a query "Select * From ... Where ... = ..."
Then I load it into a reader and
While (reader.read)
{ string sProductName = Convert.ToString(reader[1]);
/*
Now I need to display this name and all the other data
(selling price, etc) on the form
But as I do not know how many products there will be it (the form) has to change
as the database information does (more products get added or removed).
*/
}
I do not know how to do that last part. How to make the data found display on screen.
Thanks !
The data I need to display is a the Product Name, the Product Description and the Product Selling Price underneath headings with those names thats all.

For SQL Database,
Take gridview control with id="gridview1" (whatever you like but use same id in code)
SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gridview1.DataSource = ds;
gridview1.DataBind();

SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
sql.open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Textbox1.Text=dr[0].ToString();
Textbox2.Text=dr[1].ToString();
Textbox3.Text=dr[2].ToString();
......................;
}
con.close();
NOTE:
While working with datareader sql connection must be open.
I use textboxes to show the values.You can use where ever it is necessary .dr[0].ToString(),.dr[1].ToString() .....Contains the values of database table

Related

Query SQL Server using session variable

I'm trying to query a SQL Server database table based on a user variable (using ASP.NET and C#). I want to be able to pull just the user's unique records from the Waste Application Information table where the Farm Owner name is equal to the variable name (which is a string).
Here's part of my code:
conn.Open();
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = (user variable) ";
SqlCommand com = new SqlCommand(WasteAppData, conn);
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
If I replace the "(user variable)" with the actual value in the table column it does work correctly. Like this: 'Joe Smith' I've tried referencing the variable which is pulled from another webform with no luck... I think my syntax is incorrect? Any help would be great!
You need to do it this way:
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = #FarmOwn";
using (SqlCommand cmdSQL = new SqlCommand(WasteAppData , conn)
{
cmdSQL.Parameters.Add("#FarmOwn", SqlDbType.NVarChar).Value = strFarmOwnwer;
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader;
GridView1.DataBind();
}
In this case "strFarmOwner" would be replaced with your actual variable that holds the value you want.

Saving the result of Select statement from SqlDataReader to list at once

As the questions says, I'm trying to save the result of a select statement from a SqlDataReader to a list at once, rather than one by one giving the column name.
Before that I've tried using reader.read() and then giving the column name one by one and saving the data something like this,
while (reader.Read())
{
label.text = (string) reader["myColumn"];
//..... and so on repeating for all the columns in the DB.
}
Yet I've tried using IDataRecord to put all the row values in the list but it gives me NULL.
if (reader.HasRows)
{
List<string> list = (from IDataRecord r in reader
select (string)r["FieldName"]).ToList();
}
But this returns a NULL. Anyone can redirect me to proper piece of information will highly be regarded.
SqlDataReader requires you to read and move the pointer one row by one row. If you want to get all the data at once, you could use SqlDataAdapter and DataTable.
SqlConnection con = new SqlConnection("connection string");
con.Open();
SqlCommand cmd = new SqlCommand("select top 10 documentid from document order by 1 desc", con);
SqlDataReader dr = cmd.ExecuteReader();
List<string> docids = (from IDataRecord r in dr select (string)r["documentid"]).ToList<string>();
con.Close();

Add values from DB (Select Query) in a text. Asp.net

On my Homepage i made i Visual Studio i want to have some welcome text on my firstpage.
The Thing is that i want in the middle of the text present some values that i grab from my db with a select query.
Lets say for example:
Welcome to my Homepage!
Currently there are (Select Count(UserID) FROM users where Status = 'active') Users active on my page and (Select Count(UserID) FROM users where Status = 'inactive') that are inactive.
Im really new to this but somehow i Need to run the my questions on Page_load and then be able to take that value and present it in a Label or something?
Thanks for your help
Using ADO.NET:
1: Create a connection object, set it's connection string property
2: Create a command object and set its text property to
Select Count(UserID) FROM users where Status = 'active'
3: Use ExecuteScalar method of the command object to find the result you want and set the label text property equal to that result.
Procedure
create procedure select
#activity
as
Begin
Select Count(UserID) FROM users where Status = #activity
end
C# Page Load
string activity1="active";
string activity2="Inactive";
sqlconnection con=new sqlconnection("give your connection string");
sqlcommand cmd=new sqlcommand();
cmd=new sqlcommand("select",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#activity",activity1);
String result1=cmd.ExecuteNonQuery();
sqlcommand cmd1=new sqlcommand();
cmd1=new sqlcommand("select",con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#activity",activity2);
String result2=cmd.ExecuteNonQuery();
Label1.Text=result1;
Label2.Text=result2;
.aspx page
Welcome to my HomePage
Currently there are <asp:label id="Label1" runat="server"></asp:Label> Users active on my page and <asp:label id="Label2" runat="server"></asp:Label> that are inactive.
If you find this as useful and it solved your issue mark it as answer and give upvote.
Try this
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(#"MY CONNECTION");
SqlCommand com = new SqlCommand("Select Count(UserID) FROM users where Status = 'active'", con);
SqlDataReader dr;
con.Open();
while (dr.Read())
{
Debug.WriteLine(dr[0].ToString());
}
con.Close();
}

Edited value does not change while updating in website

My scenario is as follows.
I'm using ASP.NET 2.0 and VB.NET.
I have a login page. If I am an existing user, when I log in, my user details are popped in the respective textBoxes. Now I wish to change one of these fields. I edited one and then clicked on the Edit button to update the record. It's not updated but instead it brings the existing value from the text box.
How can I achieve this?
DBCmd.CommandText = "update IOMFNewMember set FirstName=#FirstName,MiddleName=#MiddleName,LastName=#LastNa,Gender=#Gender,DateofBirth=#DateofBirth,MartialStatus=#MartialStatus,DateofWedding=#DateofWedding,Nationality=#Nationality,ResidenceCountry=#ResidenceCountry,DateofJoiningIOMf=#DateofJoiningIOMf,EmailId=#EmailId,mobileno=#mobileno,AtPresent=#AtPresent,familykuwait=#familykuwait,DateofDeath =#DateofDeath where UserName=#Entery and MemberID=#MemberID"
For your requirement you have to run a sql command same as that u are using to populate the textboxes with the user details.
That is supposing you are using this in the login button click event
string strSql="select * from customers where id=" + txtLoginId.Text;
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=new SqlCommand(strSql,con);
DataSet dset=new DataSet();
da.Fill(dset);
con.Close();
You will have to use this in the edit button click event :
string strSql="update EmployeeTable set password = '" + txtPassword.Text + "'";
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlCommand cmd=new SqlCommand(strsql, con);
cmd.ExecuteScalar();
con.Close();
Hope this will clear you confusion.
This is just an example. For a real time situation its advisable to use stored procedures only for any database query.

Why SQLCommandBuider not DELETING?

In the following code UPDATE is working but DELETE is not working. When I DELETE row it delete it and GridView1 does not show it but database still has it. customers has PrimaryKey.
using (SqlConnection connection = new SqlConnection(conString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from customers", connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataTable customers = new DataTable();
adapter.Fill(customers);
// code to modify data in DataTable here
customers.Rows.RemoveAt(rowIndex);
GridView1.EditIndex = -1;
GridView1.DataSource = customers;
GridView1.DataBind();
adapter.Update(customers);
You don't want to remove the row from the DataTable but delete it.
The DataRow's DataRowState must be modified to deleted, then the DataAdapter knows that it must delete it in the datasource.
Following will delete it:
customers.Rows(rowIndex).delete();//now DataRow's DataRowState is Deleted
adapter.Update(customers); // now it's actually deleted
Futher informations: MSDN How to: Delete Rows in a DataTable
By the way, following would prevent the DataRow to be deleted, if you've changed your mind:
customers.Rows(rowIndex).RejectChanges();
The RowState will change back to Unchanged.
This works either for the DataRow or for the whole DataTable.

Resources