Create quiz application using C# and database - c#

I just finished to make the add part of a quiz, the part where admin add questions for guest.
When I clicked next button I just see the last question I added. Here is the code:
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox2.Text = (reader["Question"].ToString());
textBox3.Text = (reader["R1"].ToString());
textBox4.Text = (reader["R2"].ToString());
textBox5.Text = (reader["R3"].ToString());
textBox6.Text = (reader["R4"].ToString());
if (textBox7.Text == (reader["R_correct"].ToString()))
point = point + 1;
}
con.Close();
My problem is That I don't know why I see just the last question althoug in the table I have more than one question.

The datareader is looping through all the results and overwriting the textbox values for each row in the query.
In the code above, every time you run this, only the final row retrieved will be displayed.
You might be better retrieving the data and storing in a data structure and recoding the next button to use this.
e.g.
//Set up datatable with all questions
DataTable dt=new DataTable();
dt.column.Add("Question",typeof(string));
dt.column.Add("R1",typeof(string));
dt.column.Add("R2",typeof(string));
dt.column.Add("R3",typeof(string));
dt.column.Add("R4",typeof(string));
dt.column.Add("R_correct",typeof(int));
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
DataRow dr=dt.NewRow();
dr["Question"] = (reader["Question"].ToString());
dr["R1"] = (reader["R1"].ToString());
dr["R2"] = (reader["R2"].ToString());
dr["R3"] = (reader["R3"].ToString());
dr["R4"] = (reader["R4"].ToString());
dr["R_correct"] = (reader["R_correct"]);
dt.Rows.Add(dr);
}
con.Close();
I've used a datatable here but you could easily use a list of objects as well.
The code above just adds the data from the query into a datatable and you can then, in your next button, write code that changes the row number.
This is just a rough start but it should get you on the right track

Related

Insert and restore and search in combox?

Salam Alekom .
I have comboBox filling it from database as
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand scm = new SqlCommand();
scm.Connection = con;
scm.CommandText = "select * from com";
SqlDataAdapter adpt = new SqlDataAdapter(scm);
DataTable dt = new DataTable();
adpt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = dt.Columns["com_name"].ToString();
comboBox1.ValueMember = dt.Columns["com_id"].ToString();
Where filling with all data that store in the table from database.
This comboBox use also to insert to another table in database
This also poses no problem
The problem when making search in table to get some data. I need to get the text value that store in table and equal to text value of comboBox and sort it in position 0 of this comboBox
I made the search no problem but what property or method that allow me to put the value in position 0 with out affecting the other values that be in combobox
SqlConnection con = new SqlConnection(strcon);
con.Open();
using(SqlCommand scm2 = new SqlCommand())
{
scm2 .Connection = con;
scm2.CommandType = CommandType.StoredProcedure;
scm2 .CommandText = "SP_retrieve_data";
scm2.Parameters.AddWithValue ("#id", textBox1.Text);
SqlDataReader dr = scm2.ExecuteReader();
while (dr.Read())
{
comboBox1. = dr["com_name"].ToString();//what code accept the value
}
}

Search and display certain table element

I'm trying to search my local database table and simply display all it's columns.
I start my sending in
SearchID("1234");
My code so far:
private static void SearchID(string CostumerID)
{
string conStr = #"Data Source = C:\Users\secwp_000\documents\visual studio 2012\Projects\Module5\Module5\Orderdatabase.sdf";
DataSet ds = new DataSet();
SqlCeConnection con = new SqlCeConnection(conStr);
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con);
SqlCeDataReader dr = cmd.ExecuteReader();
SqlCeDataAdapter adapt = new SqlCeDataAdapter(cmd);
adapt.Fill(ds, "Order");
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
}
Where am I thinking wrong?
It stops on
SqlCeDataReader dr = cmd.ExecuteReader();
saying i don't have a connection. But just sounds wierd, because I've just had connection..
You have to open connection using
If(con.state.toString()=="closed")
con.open();
I observe a fault in your query why are you compare your result after fetch from database.you can directly filter in SQL query
Select * from order where table.customer_Id = customerId
You have a connection but you haven't opened it yet:
con.Open();
adapt.Fill(ds, "Order");
con.Close();
In addition you should use using statements for disposable objects like SqlConnection and SqlCommand to make sure they will be disposed properly:
using(SqlCeConnection con = new SqlCeConnection(conStr))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con))
{
}
I feel so stupid for not seeing this, haha. And it worked! But it wont display anything from the table,
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
Following instructions given to me, there is nothing wrong with this code, and it could display Order with costumerID 1234.

Retrieving values from DB to Label in C#

I have created an Entity Framework application to retrieve Database values but i want to show them in individual labels instead of a gridview??
EmployEntities2 fd = new EmployEntities2();
int idToupdate = Convert.ToInt32(TextBox1.Text);
var jj = (from bn in fd.Contacts
where bn.Id == idToupdate
select bn);
GridView1.DataSource = jj;
GridView1.DataBind();
Established a connection
SqlConnection con = new SqlConnection("CONNECTION_STRING);
SqlCommand cmd = new SqlCommand();
and then,
cmd.CommandText = "select * from table where Condition ;
cmd.Connection = con
Label1.text = ((string)cmd.ExecuteScalar());
Try this one..
You should use SQLDataReader class. Base on what type of data you have in structure you should call a different method of the SQLDataReader object. For example, if you need to retrieve an integer value and display it in a label, this is the code sinppet to do it:
string queryString = "SELECT integer_value FROM table_name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader.getSqlInt32(0).ToString();
}
reader.close();
}
This is the best I can do since you didn't provide additional info.
Check out this link for info on SqlDataReader class: SqlDataReader reference

Retrieving value from sql ExecuteScalar()

I have the following:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
Program.defaultCollection = (String)cmd.ExecuteScalar();
And I want to get the second column after executing the statement. I know it will return only one row with two columns
I have read online that I will have to read each row of the result, is there any other way?
ExecuteScalar gets the first column from the first row of the result set. If you need access to more than that you'll need to take a different approach. Like this:
DataTable dt = new DataTable();
SqlDataAdapater sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt);
Program.defaultCollection = dt.Rows[0]["defaultCollection"];
Now, I realize that the field name may not be defaultCollection, but you can fill that in.
From the MSDN documentation for ExecuteScalar:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Now, as a final bit of advice, please wrap all ADO.NET objects in a using statement. Like this:
using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// do something with `dt`
}
this will ensure they are properly disposed.
And I want to get the second column after executing the statement
It is not possible with execute scalar.
is there any other way
You have 2 options here either to use SqlDataAdapter or SqlDataReader.
For you using DataReader is a recommended approach as you don't need offline data or do other worh
by using SqlDataAdapter
using (SqlConnection c = new SqlConnection(
youconnectionstring))
{
c.Open();
/
using (SqlDataAdapter a = new SqlDataAdapter(sql, c))
{
DataTable t = new DataTable();
a.Fill(t);
if(t.Rows.Count > 0)
{
string text = t.Rows[0]["yourColumn"].ToString();
}
}
}
by using DataREader
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//read data here
string text = reader.GetString(1)
}
reader.Close();
}
SqlCommand.ExecuteScalar() can be used only when the result have just one row and one column.
If you need more than one column to be returned, you should use something like this:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
Program.defaultCollection = (String)rdr["Column1"];
Program.someOtherVar = (String)rdr["Column2"];
}
}
rdr.Close();
}
That will be the fastest way.
You can use a DataReader and read only the first column like:
IDataReader cReader = cmd.ExecuteReader();
if(cReader.Read())
{
string cText = cReader.GetString(1); // Second Column
}
ExecuteScalar only returns one value. You have to make sure your query only returns that value.
String sql = "SELECT temp.defaultCollection FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
On a side note, read on SqlParameter. You don't want to concatenate values like that, you'll have a problem when the collection property contains a quote.

asp.net print the results of a sql command

I have the following sql command:
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
How can i output the results of the following command in C# to my webpage?
If you are looking for the introductory: "How to get data on a web page?" answer, then maybe this is a little more helpful:
Add a new page MyPage.aspx to your
web application
Add a GridView to that page
On Page_Load do the code
below
{
string strSQLconnection =
"Data Source=dbServer;Initial Catalog=yourDatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
con.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
You will need to execute the SQL command, then iterate through the data. Assuming this query returns one row, your code might look like:
using (var reader = cmd.ExecuteReader()) {
if (!reader.HasRows) {
// User not found
}
else {
reader.Read(); // Advance to first row
// Sample data access
var name = reader["name"];
var otherColumnValue = reader["otherColumnName"];
}
}

Categories