display individual columns from sql result in asp.net c# - c#

I'm coding a simple application using c# asp.net. I'm getting the averages of columns. How can I get the individual values from the result and display it in a new label (label1, label2, label3....)?
I tried ExecuteScalar().ToString(); but it returns only the first column.
Below is my code:
SqlConnection con;
con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\STATDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string result = "SELECT AVG(p_tan) AS p_tang, AVG(e_tan) AS e_tang, AVG(p_rel) AS p_reli FROM statistics";
SqlCommand showresult = new SqlCommand(result, con);
con.Open();
Label1.Text = showresult.ExecuteScalar().ToString();
//Label2.Text = p_tang
//Label3.Text = e_tang
//Label4.Text = p_reli
con.Close();
Any help will be appreciated.

Use showresult.ExecuteReader() and then iterate over the row to get the values
SqlDataReader reader=showresult.ExecuteReader();
while (reader.Read())
{
Label1.Text= reader["p_tang"].ToString().Trim();
Label2.Text= reader["e_tang"].ToString().Trim();
Label3.Text= reader["p_reli"].ToString().Trim();
}

ExecuteScalar will only pull one value. You will need do either use a DataReader or DataAdapter to get multiple values from the database.

Related

Storing multiple values from an SQL select statement

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

C# SQL INSERT INTO command doesn't work

I have this code:
private void FirmaEkleB_Click(object sender, EventArgs e)
{
string query = "INSERT INTO FIRMATABLE VALUES (#CompanyName)";
SqlConnection sqlconnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, sqlconnection);
Form1 LoginForm = new Form1();
sqlconnection.Open();
command.Parameters.AddWithValue("#CompanyName", FirmaIsmiTextbox.Text);
command.ExecuteScalar();
SqlCommand com2 = new SqlCommand("Select FirmaIsmi FROM FIRMATABLE WHERE ID = 9", sqlconnection);
MessageBox.Show(com2.ExecuteScalar().ToString());
LoginForm.fillFirmaList();
}
fillFirmaList() looks like this:
public void fillFirmaList()
{
connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("SELECT * FROM FirmaTable", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable firmaTable = new DataTable();
adapter.Fill(firmaTable);
FirmaCombo.DataSource = firmaTable;
FirmaCombo.DisplayMember = "FirmaIsmi";
FirmaCombo.ValueMember = "Id";
}
I don't know what I'm doing wrong but I can't seem get my combobox to update from the table I have. The manually added rows show up but not the one that I add
Keep in mind that I'm just starting out in SQL Server and database stuff.
If more info is needed tell me.
Change your Insert query to
INSERT INTO FIRMATABLE (FirmaIsmi) VALUES (#CompanyName)
You need to include all your column names for which you are adding the VALUES.
And
change ExecuteScalar to command.ExecuteNonQuery().
Add try-catch block and see what exception does it throws after ExecuteNonQuery

Want to Fill Text Box With Access Data

In C# I want to use access data to fill my textBox I Am using ADO.Net To connect to access.So far I've got this:
OleDbConnection con = new OleDbConnection(Price.constr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=con;
cmd.CommandText = "select * from Table1";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Price.constr is my connection String.
I want to fill textBox1 with the data in the Price Column Where my row ID = 1.(For Example)
If you want to read only one record from your table then there is no need to return the whole table and use an adapter to fill a datatable. You can simply ask the database to return just the record you are interested in.
string cmdText = "select * from Table1 WHERE ID = 1";
using(OleDbConnection con = new OleDbConnection(Price.constr))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
textBox1.Text = reader["Price"].ToString();
else
textBox1.Text = "No record found";
}
}
I have enclose the connection, command and reader in an using statement because these are disposable objects and it is a good practice to destroy them when you have finished to use them. (In particular the connection could cause problems if you don't dispose it)
Notice also that I have used the constant 1 to retrieve the record. I bet that you want this to be dynamic and in this case I suggest you to look at how to PARAMETRIZE your queries. (Don't do string concatenations)

Adding data to data row of database in c#

I am facing a little problem in my code to add data to sql database attached with my program in ASP.net/C#. Here's code:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
SqlConnection cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Id from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["Id"] = TextBox1.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
Even when I entered any integer value to the text box, it shows an error message that object is not set to an instance on code:
DataRow drow = ds.Tables["TableName"].NewRow();
Please guide.
Thanks.
This seems like a very bad way of inserting data. Have you looked at the Entity Framework or Linq2Sql? Alternatively you could just use a standard SqlCommand and set the CommandText yourself.
Any of these would provide a cleaner solution.
Eg: With ADO.NET (Connecting to SQLite):
var conn = new SQLiteConnection(string.Format(Constants.SQLiteConnectionString, "db.db3"));
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction()) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO TableName (Id) VALUES (#Id)";
cmd.Parameters.AddWithValue("#Id", someTextVariable);
cmd.ExecuteNonQuery();
}
}

How to retrieve the values in asp.net form from SQL Server 2005

I want the user entered values to get displayed in the form again.. my values get entered into the SQL Server database, but I don't know how to retrieve the values again in the form.. my code is:
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI");
try
{
conn.Open();
SqlCommand cmd=new SqlCommand ("insert into timeday(project,iteration,activity,description,status,hour)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"','"+this .activity .SelectedValue +"','"+this.name2.Text+"','"+this.status .SelectedValue +"','"+this .Text1 .Text +"')",conn );
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
}
You should:
avoid SQL injection and don't just concatenate together your SQL statements! Use parametrized queries instead!
put your SqlConnection and SqlCommand objects into using blocks
when you want to call an INSERT statement, definitely do not call .ExecuteReader() on your SqlCommand - use .ExecuteNonQuery() instead...
Try something like this:
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"INSERT INTO dbo.timeday(project, iteration, activity, description, status, hour) " +
"VALUES(#Project, #Iteration, #Activity, #Description, #Status, #Hour)";
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("#Project", SqlDbType.VarChar, 100);
_cmd.Parameters["#Project"].Value = this.name1.SelectedValue.Trim();
// add other parameters the same way....
conn.Open();
int result = _cmd.ExecuteNonQuery();
conn.Close();
}
It would be even better if you:
would retrieve the connection string from a config file once, centrally, and just pass it into this method
would retrieve the values to set from your web UI in your UI code, and then call this business method on a business logic object and pass in the values you've determined
Right now, you're wildly mixing UI code (retrieving the values from the dropdowns and textboxes) with database/business logic code - this is not a very solid design.....
Update: if you want to retrieve values and display them, you can use something like this:
public DataTable GetDataForProject(string projectName)
{
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"SELECT project, iteration, activity, description, status, hour " +
"FROM dbo.timeday " +
"WHERE project = #project";
DataTable resultTable = new DataTable();
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("#Project", SqlDbType.VarChar, 100);
_cmd.Parameters["#Project"].Value = projectName;
SqlDataAdapter dap = new SqlDataAdapter(_cmd);
dap.Fill(resultTable);
}
return resultTable;
}
Of course:
you might want to select based on other criteria (that would show up in your WHERE clause)
maybe you want to use a SqlDataReader and read that data into domain objects (instead of a DataTable)
but the basic setup - have a specific method, pass in criteria, read the data with SqlConnection and SqlCommand in using blocks - will remain the same.
Once you have the DataTable, you can bind it to an ASP.NET gridview:
DataTable projectData = GetDataForProject("MyProject");
gridView1.DataSource = projectData;
gridView1.DataBind();
After inserting you need to write a query to retrieve records.
Write this
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection("Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI");
try
{
conn.Open();
SqlCommand cmd=new SqlCommand ();
cmd.CommandText="insert into timeday(project,iteration,activity,description,status,hour)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"','"+this .activity .SelectedValue +"','"+this.name2.Text+"','"+this.status .SelectedValue +"','"+this .Text1 .Text +"')";
cmd.Connection=conn;
int i=cmd.ExecuteNonQuery();
if(i>0)
{
cmd.CommandText="Select * from timeday";
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
}
finally
{
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
}

Categories

Resources