I'm getting the error 'Object reference not set to an instance of an object'. I've tried looking at similar problems but genuinely cannot see what the problem is with my program. The line of code that I am having an error with is:
labelQuestion.Text = table.Rows[0]["Question"].ToString();
Here is my code in its entirety:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Quiz_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String chosenAnswer, correctAnswer;
DataTable table;
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
//String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
labelQuestion.Text = table.Rows[0]["Question"].ToString();
radioButton1.Text = table.Rows[0]["Answer 1"].ToString();
radioButton2.Text = table.Rows[0]["Answer 2"].ToString();
radioButton3.Text = table.Rows[0]["Answer 3"].ToString();
radioButton4.Text = table.Rows[0]["Answer 4"].ToString();
correctAnswer = table.Rows[0]["Correct Answer"].ToString(); ;
conGet.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
if (radioButton1.Checked)
{
chosenAnswer = reader["Answer 1"].ToString();
}
else if (radioButton2.Checked)
{
chosenAnswer = reader["Answer 2"].ToString();
}
else if (radioButton3.Checked)
{
chosenAnswer = reader["Answer 3"].ToString();
}
else
{
chosenAnswer = reader["Answer 4"].ToString();
}
if (chosenAnswer == reader["Correct Answer"].ToString())
{
//chosenCorrectly++;
MessageBox.Show("You have got this answer correct");
//label2.Text = "You have got " + chosenCorrectly + " answers correct";
}
else
{
MessageBox.Show("That is not the correct answer");
}
}
}
}
}
I realise the problem isn't too big but I can't see how my declaration timings are wrong
You never initialize table, so it will be null when you try to access its Rows property.
You don't actually need the DataTable in this instance, though. You can access the properties directly from the OleDbDataReader (which you do initialize.) See here for details (look at the Get***() family of methods.)
Something like:
labelQuestion.Text = reader.GetString(reader.GetOrdinal("Question"));
And so forth for the rest of the columns.
If you do choose to use table, then omit the reader.Read() line and add:
table = new DataTable();
table.Load(reader);
The problem is that your table is not initialized. Therefore, when you try to access table.row[0] you get this error message.
And If there was no question column, you would probably get an error like
Column ‘Question’ does not belong to table.
Hence, at this point it is not ok. to say whether there is 'Question' column or not. First, you need to fill your table.
Right after you call ExecuteReader () in Form1_Load you need
table = new DataTable();
table.Load (reader);
Error object reference Null:
try
{
OleDbCommand com;
// OleDbConnection con = new OleDbConnection(ConnectionString);
cn.Open();
string str = "select *from DatabaseLogin where user_id='" + textBox2.Text + "'";
com = new OleDbCommand(str, cn);
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
checkedListBox1.Items.Add(reader["stckdemge"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(" " + ex);
}
Either the table has no rows, or there is no "Question" column, or that the column has a Null value in it.
Consider breaking the assignment up into multiple steps to help you diagnose the issue.
EDIT:
Or, as sharper eyes have already noted, it's because you've not assigned anything to 'table' (d'oh).
The comment about breaking up the assignment is a useful diagnostic method, though.
Related
I have a two dimensional array with 3 columns and 2 rows. I also have a database table with 3 columns. I want to insert the 2D array directly into the database.
Is there any way to that?
Any help is appreciated. I can supply more details if needed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _2DArrayIntoDatabaseTest
{
public partial class Form1 : Form
{
string[,] LoginInfo = new string[2, 3]{{"1", "Admin", "123"},{"2", "Admin2", "456"}};
string query;
SqlCommand Sqlcmd;
SqlConnection conn = new SqlConnection(#"Data Source=MIRAZ-PC\SQLEXPRESS;
Initial Catalog=2DArrayIntoDatabaseTest;
Integrated Security=True");
DataTable dbdataset;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.tTableAdapter.Fill(this._2DArrayIntoDatabaseTestDataSet.t);
}
int i = 0, j = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3;j++ )
query = "INSERT INTO t(SerialNumber,UserName,Password)
values( '" + LoginInfo[i, 0] + "','"
+ LoginInfo[i, 1] + "','"
+ LoginInfo[i, 2] + "')";
}
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
Sqlcmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
query = "SELECT * from t";
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Sqlcmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//dataGridView1.Columns.Remove("rownum");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
Now this piece of code compiles fine. But in Data Grid View I can only see 1 row instead of 2.
How to solve that?
Note: Here I am trying to use a nested loop to create a dynamic query to insert a row of data one at a time.
Instead of [i, 1], [i, 2], and [i, 3] you need [i, 0], [i, 1], and [i, 2]. Also, ExecuteNonQuery() needs to happen inside the for loop.
While I'm here, I'll also show some better practice on including data in with the SQL query. The current code is crazy-vulnerable to sql injection.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO t(SerialNumber,UserName,Password) VALUES (#serial, #user, #pass);";
var dbdataset = new DataTable();
//ADO.Net does better if you create new objects, rather than try to re-use them through a class or application.
// The "using" blocks will make sure things are closed and disposed properly, even if an exception is thrown
using (var conn = new SqlConnection(#"Data Source=MIRAZ-PC\SQLEXPRESS;Initial Catalog=2DArrayIntoDatabaseTest;Integrated Security=True"))
using (var cmd = new SqlCommand(query, conn))
{
//I had to guess at column types and lengths here.
// You should use actual column types and lengths from the DB
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#pass", SqlDbType.NVarChar, 20);
conn.Open();
for (i = 0; i < LoginInfo.GetUpperBound(0); i++)
{
cmd.Parameters["#serial"].Value = LoginInfo[i, 0];
cmd.Parameters["#user"].Value = LoginInfo[i, 1];
cmd.Parameters["#pass"].Value = LoginInfo[i, 2];
try
{
//don't forget to do this INSIDE the loop
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
cmd.CommandText = "SELECT * FROM t";
var sda = new SqlDataAdapter(cmd);
try
{
sda.Fill(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
dataGridView1.DataSource = dbdataset;
}
Last of all... plain-text passwords like this are NOT GOOD.
Here's an example using a List<UserLoginInfo>. Note moving code to the new DB class here is not required for the List to work; it's just good practice to do that anyway.
public class UserLoginInfo
{
public string SerialNumber {get;set;} //you might want an int here instead
public string Username {get;set;}
public string Password {get;set;}
}
public static class DB
{
private static readonly string ConnectionString = #"Data Source=MIRAZ-PC\SQLEXPRESS;Initial Catalog=2DArrayIntoDatabaseTest;Integrated Security=True";
public static void SaveUserData(IEnumerable<UserLoginInfo> users)
{
string query = "INSERT INTO t(SerialNumber,UserName,Password) VALUES (#serial, #user, #pass);";
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#pass", SqlDbType.NVarChar, 20);
conn.Open();
foreach(var user in users)
{
cmd.Parameters["#serial"].Value = user.SerialNumber;
cmd.Parameters["#user"].Value = user.UserName;
cmd.Parameters["#pass"].Value = user.Password;
cmd.ExecuteNonQuery();
}
}
}
public static DataTable GetLoginData()
{
var result = new DataTable();
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand("SELECT * FROM t", conn))
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(result);
}
return result;
}
}
public partial class Form1 : Form
{
private List<UserLoginInfo> LoginInfo = new List<UserLoginInfo> {
new UserLoginInfo() {SerialNumber = "1", Username = "Admin", Password = "123"},
new UserLoginInfo() {SerialNumber = "2", UserName = "Admin2", Password = "456"}
};
private void button1_Click(object sender, EventArgs e)
{
try
{
DB.SaveUserData(LoginInfo);
dataGridView1.DataSource = DB.GetLoginData();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Yes that can be done very easily. I have done this in vb.net as under.. I have taken array arr with 4 columns and two rows..
Dim Arr()() = {({1, "Document Title", "TITLE", "C"}),
({2, "Company Header1", "HEADER1", "C"})}
Now for inserting this into database you can simply run insert query for inserting data in your own way... for e.g.
for each item in arr.items
exexuteNonQuery("INSERT INTO Supplier (SupplierID, Name, abc,xyz) VALUES (#SID, #Name, #abc, #xyz)")
next
I am making a attendance system, and here is my problem now, after i searched for a name of a person and try to log him in for attendance, it is fine at first, after logging in the second name it is still fine. but once i tried to edit the login attendance of the first or second user, all the values in my datagridview(connected to my database) became duplicated. if i enter name1 for attendance in my week1 it is fine. name2 for attendance in week1 is still fine.
but if i edit the same name. or even go to the next week number, all of the saved values got duplicated based on my recent inputed name.
for inserting new records
SqlConnection cnn200 = new SqlConnection(connectionstring);
string sql200 = "SELECT * FROM attendance WHERE csign=#csign ";
cnn200.Open();
SqlCommand cmd200 = new SqlCommand(sql200, cnn200);
SqlDataReader rdr200;
cmd200.Parameters.AddWithValue("#csign", callsign);
rdr200 = cmd200.ExecuteReader();
if (rdr200.Read() == true)
{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "insert INTO attendance
(csign,name,week1)" + "VALUES" + "(#csign,#name,#week1)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "insert INTO attendance
(csign,name,week2)" + "VALUES" + "(#csign,#name,#week2)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
and for updating
else{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week1=#week1";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week2=#week2";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}`}
nica, I think I can help. What you are trying to do can be done easily with less coding lines. An entire DataGridView can be displayed, edited, deleted and have no duplicates by using a few more objects
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ADO_NET_Testbed
{
public partial class MainForm : Form
{
private SqlDataAdapter adapter;
private string connectionString = #"Data Source=Server;Persist Security Info=True;Password=password!;User ID=sooperuser;Initial Catalog=Database";
private string sqlcommand = #"SELECT OPID, LastName, FirstName, Title, PhoneOffice, PhoneCell, Email, Active, Admin, Tester, Educator, Developer FROM AuditUser";
private SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
private DataTable datatable = new DataTable();
private DataSet dataset = new DataSet();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
adapter = new SqlDataAdapter(sqlcommand, connectionString);
adapter.Fill(dataset, "AuditUser");
dgvUsers.DataSource = dataset.Tables[0];
dgvUsers.Enabled = true;
this.Show();
}
private void btnCancel_Click(object sender, EventArgs e)
{
dataset.Clear();
dataset.Reset();
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmdBuilder.DataAdapter = adapter;
adapter.Update(dataset.Tables[0]);
this.Close();
}
}
}
As a quick rundown of what is going on, the SqlDataAdapter holds the four queries, but auto-creates three from the SELECT command. Using a SqlCommandBuilder enables the other three to be added, although the debugger will not show them as anything but NULL. The adapter.Fill() and adapter.Update() handle all the different commands based on the RowState of each row in the datagridview. "Cancel" is overkill seeing as this form is closed anyway.
How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb"))
using(OleDbCommand cmd = new OleDbCommand(" SELECT * from TableAcct", conn))
{
conn.Open();
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
listBox1.Text = Reader.GetString("FirstName");
}
}
the errors are here:
1. Error 1 The best overloaded method match for'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments.
2. Error 2 Argument '1': cannot convert from 'string' to 'int'
try this one,
List<String> firstName = new List<String>();
List<String> lastName = new List<String>();
private void loadButton_Click(object sender, EventArgs e)
{
cn.Open();
OleDbDataReader reader = null;
cmd = new OleDbCommand("select* from Records", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
firstName.Add(reader["FirstName"].ToString());
lastName.Add(reader["LastName"].ToString());
}
cn.Close();
}
then in your search button, insert this,
private void searchButton_Click(object sender, EventArgs e)
{
clearSearchResult();
try
{
int totalItems = FirstName.Count;
int count = 0;
while (count < totalItems)
{
if (textBox6.Text == FirstName[count].ToString())
{
listBox1.Items.Add(FirstName[count].ToString());
count = 100;
}
else
{
count++;
}
It's good to use when you want to show the information of the "FirstName" in the listBox1_SelectedIndexChanged if you want. here's an example,
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int totalItems = lastName.Count;
int count = 0;
while (count < totalItems)
{
if ((listBox1.SelectedItem.ToString()) == firstName[count].ToString()))
{
textBox1.Text = firstName[count].ToString();
textBox2.Text = lastName[count].ToString();
count = 100;
}
else
{
count++;
}
}
hope this helps,
change
listBox1.Text = Reader.GetString("FirstName");
to
listBox1.Text = Reader.GetString(0); // zero base ordinal of column
GetString() takes an int as the parameter and not a string. Meaning that you must use the index of the column.
In your specific circumstance as "FirstName" is the second column the index would be 1:
listBox1.Text = Reader.GetString(1);
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
Thy using a While loop
while(reader.Read())
{
listbox1.Items.Add(reader["FirstName"]);
}
This moves through all the rows you selected. reader.Read() returns false if there are no more rows.
Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader instance. Like my example.
var value = reader["ColumnName"];
This increases readability comparing to
var value = reader.GetString(0);
UPDATE
If you want to only display the fist value - I suggest you use cmd.ExecuteScalar() and the adapt you sql to only return the value you need:
using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
{
conn.Open();
var firstName = cmd.ExecuteScalar();
}
Be aware the this will give you the first "FirstName" in the table. And since there is no "order by firstname" or "where someKey = 1" - this might not rturn that you expected.
If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label.
First of all create any Access data base like here "PirFahimDataBase".
Now in your Visual Studio go to the menu and do this
Click Data
Add New Data Base
Click Next
Click New Connection
Now change the Data Source by clicking Change and select Microsoft Access data base files
Click Browse for selecting your created data base
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
using System.Windows.Forms; //these two lines should be written before namespace at top of the program
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
try
{
conn.Open();
MessageBox.Show("connected successfuly");
OleDbDataReader reader = null; // This is OleDb Reader
OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label1.Text= reader["TicketNo"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}//end of button click event
Your error is in this line:
listBox1.Text = Reader.GetString("FirstName");
You must pass a number in the GetString() function.
DataColumn[] PrimaryKeyColumn = new DataColumn[1]; //Define Primary coloumn
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
ReadAndUpdateExcel.ReadExcel(strPath, sheetName, out dataSet);
dataSet.Tables.Add(dataTable);
PrimaryKeyColumn[0] = dataSet.Tables[0].Columns[0];
dataSet.Tables[0].PrimaryKey = PrimaryKeyColumn;
string num = dataSet.Tables[0].Rows[dataSet.Tables[0].Rows.IndexOf(dataSet.Tables[0].Rows.Find(strTCName))]["ACNO"].ToString();
//string country
My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ReadDataFromMysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sql = " SELECT * FROM teacher ";
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
}
}
private void btnclose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:
data2txt.Text = string.Empty;
datatxt.Text = string.Empty;
while (reader.Read())
{
data2txt.Text += $"{reader.GetString("id")};";
datatxt.Text += $"{reader.GetString("userId")};";
}
You're assigning the value of each field instead of the value of the existing control's text plus the new value. Add a breakpoint to make sure you're getting multiple rows, but as your code is written, you would only see the result of one row in your form because you're overwriting on each iteration through the loop.
This code works.
private void getdata()
{
MySqlConnection connect = new MySqlConnection("SERVER=localhost; user id=root; password=; database=databasename");
MySqlCommand cmd = new MySqlCommand("SELECT ID, name FROM data WHERE ID='" + txtid.Text + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("ID");
txtname.Text = dr.GetString("name");
}
dr.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}
Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.
You should output the data before again writing in it:
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
Or use a var to store all the data in with each 'read' and then output that var
varexample.Text += reader.GetString("id");
I am making a quiz which was working up to a point but after trying to increase its complexity it doesn't work completely as it should. All that happens at the moment is that the possible answers in my Access database table are binded to each radio button on my C# form.
This part is OK, however, it is no longer telling me after clicking on my button whether or not the answer I have selected is correct or not. I am using a label at the moment to tell the user if the answer is correct.
Here is my code:
namespace WindowsFormsApplication1
{
public partial class quizQuestions : Form
{
public quizQuestions()
{
InitializeComponent();
}
//int questionNumber;
//String correctAnswer;
private void WindowsAnalysisQuiz_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\quizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM quizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
label1.Text = reader["Question"].ToString();
radioButton1.Text = reader["Answer 1"].ToString();
radioButton2.Text = reader["Answer 2"].ToString();
radioButton3.Text = reader["Answer 3"].ToString();
radioButton4.Text = reader["Answer 4"].ToString();
correctAnswer = reader["Correct Answer"].ToString();
//questionNumber = 1;
conGet.Close();
}
private void btnNextQuestion_Click(object sender, EventArgs e)
{
String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\quizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
//cmdGet.CommandText = "SELECT * FROM quizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
String chosenAnswer = "";
int chosenCorrectly = 0;
if (radioButton1.Checked)
{
chosenAnswer = reader["Answer 1"].ToString();
}
else if (radioButton2.Checked)
{
chosenAnswer = reader["Answer 2"].ToString();
}
else if (radioButton3.Checked)
{
chosenAnswer = reader["Answer 3"].ToString();
}
else
{
chosenAnswer = reader["Answer 4"].ToString();
}
if (chosenAnswer == reader["Correct Answer"].ToString())
{
//chosenCorrectly++;
label2.Text = "You have got this answer correct";
//label2.Text = "You have got " + chosenCorrectly + " answers correct";
}
else
{
MessageBox.Show("That is not the correct answer");
}
}
}
}
}
So to summarise, the possible answers are loaded into the form OK, but when I press the button on the form to determine if the correct answer has been chosen, nothing at all happens.
You are not binding the btnNextQuestion_Click anywhere in your code, and you are not giving a cmdGet.CommandText in your btnNextQuestion_Click function. You may have to be more specific on what doesnt happen. Have you debugged it?
If truly "nothing" happens, then you should check that the click event of the button is still bound to the event handler.
You have commented out the line where you set the CommandText for the query, so you are trying to execute the command with not query set, which should give you an exception.
I think there is something terribly wrong in what you have got there. You are assigning the answers to the Text property and already have the correct answer in a string.
Just check the same against the checked RadioButton Text and you would know.
Also its difficult to guess what you are querying in the btnNextQuestion_Click event and i have my reservations as its actually the same question which is currently displayed and with an answer chosen by the user.