I have a set of questions in my database and I need to retrieve them in a random order every time.
Can someone please help me out with the C# code? I'm using Visual Studio 2012.
Thanks in advance.
Here's the code I'm using at the moment:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class perform_test : System.Web.UI.Page
{
public int CurrentPage
{
get
{
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0;
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Session["Company"]);
if (!Page.IsPostBack)
{
Session.Add("CorrectAnswers", 0);
//Session.Add("Questions", 0);
Session.Add("Answer", "");
}
if (repeat_exam_data.Controls.Count > 0)
{
for (int i = 1; i <= 4; i++)
{
RadioButton rad = repeat_exam_data.Controls[0].FindControl("Choice" + i.ToString()) as RadioButton;
if (rad.Checked)
{
Session["Answer"] = rad.Text;
break;
}
}
}
GetPage();
}
protected void GetPage()
{
DataTable exam_data = new DataTable();
exam_data = BussinessLayer.GetExamData(Session["Company"].ToString(), Session["Subject"].ToString(), Session["ExamId"].ToString());
PagedDataSource pgds = new PagedDataSource();
pgds.DataSource = exam_data.DefaultView;
pgds.AllowPaging = true;
pgds.PageSize = 1;
pgds.CurrentPageIndex = CurrentPage;
repeat_exam_data.DataSource = pgds;
repeat_exam_data.DataBind();
Cmd_Next.Enabled = !pgds.IsLastPage;
Cmd_Finish.Enabled = pgds.IsLastPage;
lblQno.Text = Convert.ToString((CurrentPage + 1));
lblCorrectAnswers.Text = Session["CorrectAnswers"].ToString();
}
protected void Cmd_Next_Click(object sender, EventArgs e)
{
CalculateMark();
CurrentPage += 1;
GetPage();
}
protected void Cmd_Finish_Click(object sender, EventArgs e)
{
CalculateMark();
string strSql = "INSERT INTO tbl_result(ExamId,StudentId,Mark) VALUES('" + Session["ExamId"] + "','" + Session["uname"] + "','" + Session["CorrectAnswers"] + "')";
BussinessLayer.PutData(strSql);
Response.Redirect("~/canexamresult.aspx");
}
private void CalculateMark()
{
HiddenField ans = repeat_exam_data.Controls[0].FindControl("Answer") as HiddenField;
if (Session["Answer"].ToString() == ans.Value)
Session["CorrectAnswers"] = (int)Session["CorrectAnswers"] + 1;
}
}
This code dosn't contain code responsible for feaching data. It is inside
BussinessLayer.GetExamData() probably.
You can achive random order for example by using
ORDER BY NEWID()
at the end of the query.
You can either use
ORDER BY NEWID();
as Sleipneir proposed, or load the whole whole set of data into a list, and eat that list in a random fashion.
Related
I'm working on an application that has the user fill out the four fields on the left and click the "Add Car" button and the Model, Color, and Year would appear as an listbox item and once they select that listbox item a messagebox would appear giving the user the price they wrote in the price field earlier. I've got everything to work except having the messagebox appear when I click on the listbox item. I'm not sure why it's not working.
Here I've included my code for this project. I used Visual Studio 2017 and the type of project is a Visual C# Windows Form App project if that helps:
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;
namespace MIS_312_Extra_Challenge_Project
{
public partial class Form1 : Form
{
string model, color, details = "", AllDetails = "", models = "";
int year;
double price;
public Form1()
{
InitializeComponent();
}
private void btn_addCar_Click(object sender, EventArgs e)
{
model = txtModel.Text;
color = txtColor.Text;
year = Convert.ToInt32(txtYear.Text);
price = Convert.ToDouble(txtPrice.Text);
details = model + " " + color + " " + year + Environment.NewLine;
AllDetails = AllDetails + price + " " + Environment.NewLine;
models = models + model + " " + Environment.NewLine;
list_carDetails.Items.Add(details);
txtModel.Clear();
txtColor.Clear();
txtYear.Clear();
txtPrice.Clear();
txtModel.Clear();
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void list_carDetails_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void list_carDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string[] all = AllDetails.Split();
string[] m = models.Split();
string[] modelName = { };
int i;
foreach (var car in list_carDetails.SelectedItems)
{
string details = car.ToString();
modelName = details.Split();
}
for(i=0;i<m.Length;i++)
{
if (string.Compare(modelName[0],m[i])== 0)
{
MessageBox.Show("The price of the " + modelName[0] + " is $" + all[i]);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.
I would like to learn how to make a progressbar like the one shown in this video.
I tried to replicate it in VS C#, but I get the error:
C# Property or indexer cannot be assigned to -- it is read only
If I try using if (txProgressBar.Text.Length == 85), I will get this in the TextBox (txProgressBar)
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox, Text: Syst...██
Textbox Progressbar Tutorial VB 2010
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;
namespace CustomizedProgressBar
{
public partial class Form1 : Form
{
int last = 1;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (txProgressBar.Text.Length = "85")
{
timer1.Stop();
MessageBox.Show("Counted!");
}else
{
if (last == 1)
{
txProgressBar.Text = txProgressBar + "█";
last = 2;
}
else
{
txProgressBar.Text = txProgressBar.Text + "█";
last = 1;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txProgressBar.Text = "";
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
Your line:
txProgressBar.Text = txProgressBar + "█";
should be
txProgressBar.Text = txProgressBar.Text + "█"; or txProgressBar.Text &= "█";
I realized what was the problem. The txProgressBar.Text = txProgressBar + "█"; was missing the *.Text. That solved the problem and the message is shown as well.
All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
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;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.
I have a Form with two ListBoxes on them. I have removeFromBoxWaiting that watches for creating of new files in a directory.
Once a file is created it prints it out and then it should add the name of the file into the list box.
My problem is that the list box does not get updated. Items actually have been added but they do not show and i have tried update() as well but it didn't work. So any tips will be appreciated. Thanks in advance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using System.Threading;
using System.Configuration;
namespace PrntToKitchen
{
public partial class PrintFiles : DevExpress.XtraBars.Ribbon.RibbonForm
{
FileSystemWatcher filesWatcher = new FileSystemWatcher();
public void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
MessageBox.Show(e.Item.Name);
if (Properties.Settings.Default[e.Item.Name + "Read"].ToString().Length > 1 && Properties.Settings.Default[e.Item.Name + "ExtIn"].ToString().Length > 1)
{
filesWatcher.Path = Properties.Settings.Default[e.Item.Name + "Read"].ToString();
filesWatcher.Created += new System.IO.FileSystemEventHandler(eventG);
//filesWatcher.Deleted += new System.IO.FileSystemEventHandler(addToBoxFinished);
filesWatcher.EnableRaisingEvents = true;
}
}
public void eventG(object sender, FileSystemEventArgs e)
{
string CurrentPrinter = "";
string findPrt = e.FullPath.Substring(0, e.FullPath.Length-(e.Name.Length + 1));
string findPrtExt = e.Name.Substring(e.Name.LastIndexOf("."));
for (int i = 1; i <= Properties.Settings.Default.NumberOfPrinters; i++)
{
string testPrt = Properties.Settings.Default["Printer" + i + "Read"].ToString();
string testExt = Properties.Settings.Default["Printer" + i + "ExtIn"].ToString();
if (testPrt == findPrt && testExt == findPrtExt)
{
CurrentPrinter = "Printer" + i.ToString();
POSPrinter printer = new POSPrinter(Properties.Settings.Default["Printer" + i + "Port"].ToString(), (int)Properties.Settings.Default["Printer" + i + "Speed"]);
addToBoxWaiting(e.FullPath.ToString());
string file = e.FullPath;
printer.BeginPrint();
printer.PrintFile(file);
printer.EndPrint();
printer.Dispose();
if ((bool)Properties.Settings.Default[CurrentPrinter + "Delete"])
{
IsFileLocked(file);
System.IO.File.Delete(file);
}
else
{
System.IO.File.Move(file, Properties.Settings.Default[CurrentPrinter + "Store"] + "\\" + e.Name + Properties.Settings.Default[CurrentPrinter + "ExtOut"]);
}
removeFromBoxWaiting(e.FullPath.ToString());
addToBoxFinished(e.FullPath.ToString());
busy = false;
break;
}
}
}
void addToBoxWaiting(string text)
{
listBox1.Items.Add(text);
}
void removeFromBoxWaiting(string text)
{
listBox1.Items.Remove(text);
}
public void addToBoxFinished(string destination)
{
listBox2.Items.Add(destination);
}
}
}
I believe your problem is that you are trying to add/remove listbox items while iterating through a loop (and both this actions are happening on UI thread). You should move your for loop into a separate thread, and your addToBoxWaiting method will then look like this:
private void AddToListBox(string item)
{
MethodInvoker del = delegate
{
listBox1.Items.Add(item);
};
BeginInvoke(del);
}
Edit. Added thread code.
public void eventG(object sender, FileSystemEventArgs e)
{
Thread eventThread = new Thread(ThreadProcEventG);
eventThread.Start(e);
}
private void ThreadProcEventG(object eventArgs)
{
var e = (FileSystemEventArgs)eventArgs;
string CurrentPrinter = "";
string findPrt = e.FullPath.Substring(0, e.FullPath.Length-(e.Name.Length + 1));
string findPrtExt = e.Name.Substring(e.Name.LastIndexOf("."));
for (int i = 1; i <= Properties.Settings.Default.NumberOfPrinters; i++)
{
string testPrt = Properties.Settings.Default["Printer" + i + "Read"].ToString();
string testExt = Properties.Settings.Default["Printer" + i + "ExtIn"].ToString();
if (testPrt == findPrt && testExt == findPrtExt)
{
CurrentPrinter = "Printer" + i.ToString();
POSPrinter printer = new POSPrinter(Properties.Settings.Default["Printer" + i + "Port"].ToString(), (int)Properties.Settings.Default["Printer" + i + "Speed"]);
addToBoxWaiting(e.FullPath.ToString());
string file = e.FullPath;
printer.BeginPrint();
printer.PrintFile(file);
printer.EndPrint();
printer.Dispose();
if ((bool)Properties.Settings.Default[CurrentPrinter + "Delete"])
{
IsFileLocked(file);
System.IO.File.Delete(file);
}
else
{
System.IO.File.Move(file, Properties.Settings.Default[CurrentPrinter + "Store"] + "\\" + e.Name + Properties.Settings.Default[CurrentPrinter + "ExtOut"]);
}
removeFromBoxWaiting(e.FullPath.ToString());
addToBoxFinished(e.FullPath.ToString());
busy = false;
break;
}
}
}
You may try the following code:
listBox.Dispatcher.Invoke(ew Action(()=>listBox.Item.Add(item))