I am trying to get my program to read a value from a particular cell in my Access database so that I can assign that value to the text property of a radio button. I am however getting an error I can't figure out the problem to. This is my code:
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\\WindowsAnalysisQuiz.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.CommansText = "SELECT
cmdGet.CommandText = "SELECT Question FROM WindowsAnalysisQuiz ORDER BY rnd()";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
label1.Text = reader["Question"].ToString();
radioButton.Text = cnString["Quiz"].Rows[0]["Correct Answer"].ToString();
radioButton1.Text = reader["Answer2"].ToString();
radioButton2.Text = reader["Answer3"].ToString();
radioButton3.Text = reader["Answer4"].ToString();
conGet.Close();
}
}
I am having the problem with the line beginning with radioButton.Text. Apparently it has some invalid arguments and argument 1 cannot convert from string to int
It looks like you are using several different RadioButtons, when you might really want a RadioButtonList.
If you have a RadioButtonList, it is easy to bind something to it, in essence create a list (from your database or whatever) and then bind this to the radio button list..something like
var de = new List<string>();
de.Add("1");
de.Add("2");
de.Add("3");
RadioButtonList1.DataSource = de;
RadioButtonList1.DataBind();
Shouldn't your code be something like the following:
radioButton.Text = reader["Correct Answer"].ToString();
And change your select statement to:
cmdGet.CommandText = "SELECT Question, [Correct Answer], Answer2, Answer3, Answer4 FROM WindowsAnalysisQuiz ORDER BY rnd()";
Related
I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;
Totally two drop downs
Getting values from database like:
Drop DOWN 1(Products)
Ice Cream
Chocolates
Cool Drinks
if from first drop down list 1 selected Ice cream it will display
Drop Down 2(varieties)
Vanilla
Strawberry
Mango
if from first drop down list 1 selected Chocolates it will display
Drop Down 2(varieties)
Dark chocolate
Milk Chocolate
Caramel Chocolate
Other items should clear and displays the above only
Code Used
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string txtval = DropDownList1.SelectedValue;
string txtval1 = DropDownList1.SelectedItem.Text;
string str = "Provider=Microsoft.ACE.OleDB.12.0; Data Source=C:\\Users\\user\\Desktop\123\\WebSite1\\Checking_Db.mdb";
OleDbConnection db = new OleDbConnection(str);
db.Open();
// string st = "select Emp_Ph_No from emp where Emp_Name = DropDownList1.SelectedValue ;";
string st = "select Emp_Ph_No from emp where Emp_Name = txtval1;";
OleDbCommand dbc = new OleDbCommand(st, db);
OleDbDataReader read = dbc.ExecuteReader();
DropDownList2.DataSource = read;
DropDownList2.DataTextField = "variety";
DropDownList2.DataValueField = ""variety";
DropDownList2.DataBind();
read.Close();
db.Close();
}
Problem on that line;
...where Emp_Name = txtval1;
If txtval1 is a string, you would use it as Emp_Name = 'txtval1'. This is not a valid syntax. In that case, OLEDB provider thinks this txtval1 is a parameter and you didn't suplied any value for that.
You can set this value as a parameter and add to your command like;
string st = "select Emp_Ph_No from emp where Emp_Name = ?";
OleDbCommand dbc = new OleDbCommand(st, db);
dbc.Parameters.AddWithValue("?", txtval1);
I used AddWithValue in my example but you don't. This method may generate unexpected results sometimes. Use .Add() overloads to specify your parameter OleDbType and it's size.
Also use using statement to dispose your connection, command and reader automatically instead of callind .Close or .Dispose methods manually.
using(var db = new OleDbConnection(str))
using(var dbc = db.CreateCommand)
{
// Set your CommandText.
// Add your parameter value.
using(var read = dbc.ExecuteReader())
{
//
}
}
In my winform, there's a datatable with 2 column, 1st one is studentname & 2nd column is StudentAverage.
First txtbx is autosuggest(studentname).
How to make the second txtbx automaticaly fill according to 1st txtbx (2nd txtbx fill with the corresponding record of second column (studentsavrage)?
this is for the 1st txtbx; shows StudentNames
private void txtbxName_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string StrCmd = "SELECT * FROM School";
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\School_Database.accdb";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
OleDbCommand Cmd = new OleDbCommand(StrCmd, MyConn); ;
OleDbDataReader ObjReader = Cmd.ExecuteReader();
if (ObjReader != null)
{
while (ObjReader.Read())
namesCollection.Add(ObjReader["StudentName"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
ObjReader.Close();
MyConn.Close();
txtbxName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtbxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtbxName.AutoCompleteCustomSource = namesCollection;
}
I assume you are developing with WinForms.
First out: since a where clause is missing from your query you are not filtering while user inputs text. You should move AutoCompleteStrinCollection fetching in another place if you don't want that.
Your problem: the simplier way here is to manually update the second textbox in your txtbxName_TextChanged method.
private void txtbxName_TextChanged(object sender, EventArgs e)
{
string StrCmd = String.Format( "SELECT AGE FROM School WHERE name '{0', txtbox1.Text");
//perform query as you already do and read result
textbox2.Text = cmd.ExecuteScalar()
}
P.S: in real world things are not done the way you are doing under many many aspects
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.
i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command
ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}