My online exam application test in asp.net gets split when multiple users take the test. my 20 question test gets split into 10 10 question to each user who is taking the test simultaniously. I am using session in my appliaction here is the code please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using BAL;
namespace OnlineExamDesign
{
public partial class Exam : System.Web.UI.Page
{
static int index = 0;
static int selection = 0;
static int QuestionNums = 0;
clsExam examObj = new clsExam();
DataSet ds; DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
index = 0;
selection = 0;
string set = Session["CandidateSet"].ToString();
ds = examObj.getQuestion(set);
Session["Ques"] = ds;
displayQuestion(index);
btnPrevious.Enabled = false;
if (Session["candidateName"] != null)
lblCandidateName.Text = Session["candidateName"].ToString();
clearResultData();
}
}
private void clearRadioButtons()
{
rbtnOption1.Checked = false;
rbtnOption2.Checked = false;
rbtnOption3.Checked = false;
rbtnOption4.Checked = false;
}
private void clearResultData()
{
for (int n = 0; n < clsExam.AnsList.Length; n++)
{
clsExam.AnsList[n] = 0;
}
}
private void saveCandidateData()
{
Candidate obj = new Candidate();
obj.Fname = Session["CandidateFName"].ToString();
obj.Lname = Session["CandidateLName"].ToString();
obj.Contact = Session["CandidateContact"].ToString();
obj.Domain = Session["CandidateDomain"].ToString();
obj.Team = Session["CandidateTeam"].ToString();
obj.Set = Session["CandidateSet"].ToString();
obj.ExamStartTime = (DateTime)Session["strttime"];
obj.ExamEndTime = System.DateTime.Now;
obj.Score = examObj.score;
obj.actionCandidateDetails("save");
Session["Score"] = obj.Score;
}
private int displayQuestion(int index)
{
ds = (DataSet)Session["Ques"];
dt = ds.Tables[0];
int num = dt.Rows.Count;
if (index <= num)
{
lblQuestionNum.Text = Convert.ToString((index+1));
lblQuestion.Text = dt.Rows[index]["questions_question_nvc"].ToString();
rbtnOption1.Text = dt.Rows[index]["questions_option1_nvc"].ToString();
rbtnOption2.Text = dt.Rows[index]["questions_option2_nvc"].ToString();
rbtnOption3.Text = dt.Rows[index]["questions_option3_nvc"].ToString();
rbtnOption4.Text = dt.Rows[index]["questions_option4_nvc"].ToString();
}
else if (index > num - 1)
btnNext.Enabled = false;
else if (index <= 0)
btnPrevious.Enabled = false;
return num;
}
private void retainChoice()
{
if ((clsExam.AnsList[index]).Equals(1))
{
rbtnOption1.Checked = true;
}
else if ((clsExam.AnsList[index]).Equals(2))
{
rbtnOption2.Checked = true;
}
else if ((clsExam.AnsList[index]).Equals(3))
{
rbtnOption3.Checked = true;
}
else if ((clsExam.AnsList[index]).Equals(4))
{
rbtnOption4.Checked = true;
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
btnPrevious.Enabled = true;
rbtnOptionCheckedChanged(sender, e);
examObj.storeAns(index, selection);
selection = 0;
clearRadioButtons();
index++;
int QuestionNums = displayQuestion(index);
retainChoice();
if (index >= QuestionNums - 1)
btnNext.Enabled = false;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
if (index > 0)
{
rbtnOptionCheckedChanged(sender, e);
examObj.storeAns(index, selection);
selection = 0;
clearRadioButtons();
index--;
displayQuestion(index);
retainChoice();
btnNext.Enabled = true;
}
else if (index <= 0)
{
btnPrevious.Enabled = false;
}
else if (index < QuestionNums - 1)
{
btnNext.Enabled = true;
}
else
{
btnPrevious.Enabled = false;
btnNext.Enabled = true;
}
}
protected void btnExit_Click(object sender, EventArgs e)
{
int i = 0;
examObj.storeAns(index, selection);
ds = (DataSet)Session["Ques"];
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["questions_answer_nvc"].Equals(clsExam.AnsList[i]))
{
examObj.countScore();
i++;
}
}
Response.Write(examObj.score);
saveCandidateData();
index = 0;
clearResultData();
Response.Redirect("ThankYou.aspx");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int i = 0;
examObj.storeAns(index, selection);
ds = (DataSet)Session["Ques"];
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["questions_answer_nvc"].Equals(clsExam.AnsList[i]))
{
examObj.countScore();
i++;
}
}
Response.Write(examObj.score);
saveCandidateData();
index = 0;
clearResultData();
Response.Redirect("ThankYou.aspx");
}
protected void rbtnOptionCheckedChanged(object sender, EventArgs e)
{
if (rbtnOption1.Checked)
selection = 1;
else if (rbtnOption2.Checked)
selection = 2;
else if (rbtnOption3.Checked)
selection = 3;
else if (rbtnOption4.Checked)
selection = 4;
}
}
}
I am going to repeat the sentence I am famous for in our company: Static is evil!
And yes, it is. static in a web application means it is shared across all users, meaning that the index of user 1 is the same as the index for user 2.
You can fix this quite easily by storing your static variables in the session object. I would simply hide that in a property:
public int Index
{
get
{
return (Session["Exam_Index"] as int?) ?? 0;
}
set
{
Session["Exam_Index"] = value;
}
}
Related
I need to display an unselected ComboBox value.
I have 10 ComboBoxes with tag values 1 through 10.
When I select a ComboBox with a tag value of 1, I have to check what is displayed from the ComboBox that has a tag value of 2.
Selecting a ComboBox with a tag value of 5 should give me the value of the ComboBox that has a tag value of 6.
public partial class workPlacePlan : Form
{
public workPlacePlan()
{
InitializeComponent();
}
private void workPlacePlan_Load(object sender, EventArgs e)
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
int cboId;
int i = 1;
string cboName; int c = 1;
var items = new Dictionary<int, string>();
ComboBox[] cbo = {
cbo_1, cbo_2
};
foreach(ComboBox cbos in cbo)
{
items.Add(0, "-------");
i = 1;
while (i <= 24)
{
cboId = i;
cboName = TimeSpan.FromHours(i).ToString("hh':'mm");
items.Add(cboId, cboName);
i++;
}
cbos.Tag = c;
cbos.DataSource = new BindingSource(items, null);
cbos.DisplayMember = "Value";
cbos.ValueMember = "Key";
items.Clear();
cbos.SelectedIndexChanged += new EventHandler(cboSelected);
c++;
}
}
public void cboSelected(object sender, EventArgs e)
{
ComboBox cb = ((ComboBox)sender);
int i_tmp;
int tg = Int32.Parse(cb.Tag.ToString());
if(tg % 2 == 0) //if is even
{
i_tmp= tg - 1;
}
else
{
i_tmp = tg + 1;
}
}
private void cmd_Save_Click(object sender, EventArgs e)
{
}
}
Solution:
public partial class workPlacePlan : Form
{
public workPlacePlan()
{
InitializeComponent();
}
private void workPlacePlan_Load(object sender, EventArgs e)
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
int cboId;
int i = 1;
string cboName; int c = 1;
var items = new Dictionary<int, string>();
ComboBox[] cbo = {
cbo_1_0, cbo_1_1, cbo_2_0, cbo_2_1, cbo_3_0, cbo_3_1, cbo_4_0, cbo_4_1, cbo_5_0, cbo_5_1, cbo_6_0, cbo_6_1,
cbo_13_0,cbo_13_1,cbo_14_0,cbo_14_1,cbo_15_0,cbo_15_1,cbo_16_0,cbo_16_1,cbo_17_0,cbo_17_1,cbo_18_0,cbo_18_1,
cbo_19_0,cbo_19_1
};
foreach(ComboBox cbos in cbo)
{
items.Add(0, "-------");
i = 1;
while (i <= 24)
{
cboId = i;
cboName = TimeSpan.FromHours(i).ToString("hh':'mm");
items.Add(cboId, cboName);
i++;
}
cbos.Tag = c;
cbos.DataSource = new BindingSource(items, null);
cbos.DisplayMember = "Value";
cbos.ValueMember = "Key";
cbos.SelectedIndex = 0;
items.Clear();
cbos.SelectedIndexChanged += new EventHandler(cboSelected);
c++;
}
}
public void cboSelected(object sender, EventArgs e)
{
ComboBox cb = ((ComboBox)sender);
int i_tmp;
int tg = Int32.Parse(cb.Tag.ToString());
int idx;
if(tg % 2 == 0) //if is even
{
i_tmp= tg - 1;
}
else
{
i_tmp = tg + 1;
}
//string y = cb.GetItemText(cb.SelectedItem);
//MessageBox.Show(y.ToString());
foreach (ComboBox cbt in panel1.Controls.OfType<ComboBox>()) {
if(Int32.Parse(cbt.Tag.ToString()) == Int32.Parse(i_tmp.ToString()))
{
idx = Int32.Parse(cbt.SelectedIndex.ToString());
cbt.SelectedIndex = idx;
MessageBox.Show(cbt.SelectedIndex.ToString());
}
}
}
private void cmd_Save_Click(object sender, EventArgs e)
{
}
}
Image of the application
So there are 4 columns ID,ItemName,ItemCategory and PriceAmount
What i want to do is sort the price amount by clicking the dropdown menu and i took out the price amount added it in an arrray and then sorted it using bubble sort but i am having a hard time finding out how do i update the datagridview as per the price amount and changing its respective columns too any help?
This is what i did
int[] price = new int[dataGridView1.Rows.Count];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
price[i] = Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
for (int j = 0; j < price.Length; j++)
{
Console.WriteLine(price[j]);
}
}
int temp;
for (int j = 0; j <= price.Length - 2; j++)
{
for (int i = 0; i <= price.Length - 2; i++)
{
if (price[i] > price[i + 1])
{
temp = price[i + 1];
price[i + 1] = price[i];
price[i] = temp;
}
}
}
foreach(int sortedArray in price)
{
Console.Write(sortedArray + " ");
Console.ReadLine();
}
here is the code of the browse button
private void browseBtn_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Files(*.txt, *.csv)|*.txt;*.csv|All Files (*.*) |*.*";
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
pathTextBox.Text = dialog.FileName;
}
if(pathTextBox.Text.Length>0)
{
importBtn.Enabled = true;
}
}
then it grabs the location of the .csv file and then adds in the textbox
and then the insert button imports it
private void importBtn_Click(object sender, EventArgs e)
{
string value = pathTextBox.Text;
importCSVDataFile(value);
pathTextBox.Text = "";
}
Code of importCSVDataFile
private void importCSVDataFile(string filepath)
{
try
{
TextFieldParser csvreader = new TextFieldParser(filepath);
csvreader.SetDelimiters(new string[] { "," });
csvreader.ReadFields();
//int row_count = 0;
while (!csvreader.EndOfData)
{
string[] fielddata = csvreader.ReadFields();
dataGridView1.Rows.Add();
for (int i = 0; i < fielddata.Length; i++)
{
dataGridView1.Rows[row_count].Cells[i].Value = fielddata[i];
}
row_count++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Import CSV File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I was performing a insert and update work with this
private void insertBtn_Click(object sender, EventArgs e)
{
string id = idTextBox.Text;
string itemName = itemNameTextBox.Text;
string itemCategory = categoryTextBox.Text;
string itemPrice = priceTextBox.Text;
if (this.status)
{
dataGridView1.Rows[this.row].Cells[0].Value = id;
dataGridView1.Rows[this.row].Cells[1].Value = itemName;
dataGridView1.Rows[this.row].Cells[2].Value = itemCategory;
dataGridView1.Rows[this.row].Cells[3].Value = itemPrice;
this.insertBtn.Text = "Save";
dataGridView1.Rows[this.row].Selected = true;
MessageBox.Show("Existing Record Updated");
}
else
{
int count = dataGridView1.Rows.Count;
dataGridView1.Rows[count].Cells[0].Value = id;
dataGridView1.Rows[count].Cells[1].Value = itemName;
dataGridView1.Rows[count].Cells[2].Value = itemCategory;
dataGridView1.Rows[count].Cells[3].Value = itemPrice;
dataGridView1.Rows[count].Selected = true;
MessageBox.Show("New Record Saved!!");
row_count++;
}
itemNameTextBox.Text = "";
categoryTextBox.Text = "";
priceTextBox.Text = "";
this.status = false;
this.row = 0;
}
Sort Algorithm of Bubble Sort for itemName
private void sortByItem()
{
int rows = dataGridView1.Rows.Count;
for (int i = 0; i < rows; i++)
{
for (int j = 1; j < rows; j++)
{
string val1 = Convert.ToString(dataGridView1.Rows[j - 1].Cells[0].Value);
string val2 = Convert.ToString(dataGridView1.Rows[j].Cells[0].Value);
if (string.Compare(val1, val2) > 0)
{
for (int a = 0; a < this.dataGridView1.Columns.Count; a++)
{
object temp = this.dataGridView1[a, j - 1].Value;
this.dataGridView1[a, j - 1].Value = this.dataGridView1[a, j].Value;
this.dataGridView1[a, j].Value = temp;
}
}
}
}
The way you are binding data in the gridview is not right. That way you can not achieve functionality of sorting GridView.
What you need is a class which represents the data which are loading in the gridview.
Let say you have a product class as following.
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public double Price { get; set; }
}
Now you have data of multiple products in the file so you need to create a list of products and initialize it in the form as following.
public partial class Form1 : Form
{
private List<Product> products;
public Form1()
{
products = new List<Product>();
InitializeComponent();
}
}
Now method importCSVDataFile needs to be changed as following to load data from the file and populate the list and bind it to the grid view.
private void importCSVDataFile(string filepath)
{
try
{
TextFieldParser csvreader = new TextFieldParser(filepath);
csvreader.SetDelimiters(new string[] { "," });
csvreader.ReadFields();
while (!csvreader.EndOfData)
{
string[] fielddata = csvreader.ReadFields();
var product = new Product();
product.ID = Convert.ToInt32(fielddata[0]);
product.Name = fielddata[1];
product.Category = fielddata[2];
product.Price = Convert.ToDouble(fielddata[3]);
products.Add(product);
}
dataGridView1.DataSource = products;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Import CSV File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Once you have data displayed in the grid, you need to change sorting code as following.
Let say you have combobox1 which has column names listed to sort the gridview. So code of combobox1's SelectedIndexChanged event will be as following.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
var selectedColumnName = comboBox1.SelectedItem as string;
switch (selectedColumnName)
{
case "ID":
dataGridView1.DataSource = products.OrderBy(product => product.ID).ToList();
break;
case "Name":
dataGridView1.DataSource = products.OrderBy(product => product.Name).ToList();
break;
case "Category":
dataGridView1.DataSource = products.OrderBy(product => product.Category).ToList();
break;
case "Price":
dataGridView1.DataSource = products.OrderBy(product => product.Price).ToList();
break;
}
}
}
To add new products to the gridview you need to create new instance of Product and set its properties and then add it to the list and bind the list to the gridview again.
public void btnInsert_Click(object sender, EventArgs e)
{
var id = Convert.ToInt32(txtId.Text);
var objProduct = products.FirstOrDefault(product => product.ID == id);
if (objProduct == null)
{
objProduct = new Product();
objProduct.ID = id;
objProduct.Name = txtName.Text;
objProduct.Category = txtCategory.Text;
objProduct.Price = Convert.ToDouble(txtPrice.Text);
products.Add(objProduct);
}
else
{
objProduct.Name = txtName.Text;
objProduct.Category = txtCategory.Text;
objProduct.Price = Convert.ToDouble(txtPrice.Text);
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = products;
}
I hope this would help you resolve your issue.
I am looking to store values from a CSV file with two Columns, I have the following class ReadFromCSVhandling the reading of the CSV file but I am having difficulty using this list to display the contents once a button is clicked. The code I have to read the CSV file is as follows;
namespace ELMFS
{
public class ReadFromCSV
{
static void ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
}
}
public class TextSpeak
{
string Abreviated;
string Expanded;
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
I am trying to display the textSpeak.Abreviated in a message box but cannot seem to access it from the WPF window.
How do I use this list in other windows within the application?
any advice would be appreciated!
Thanks in advance!
First, ReadCSV method should return the generated List object (or you cannot use the list anywhere else).
Second, TextSpeak class should have properties so that you can access its member variables outside the class.
I.e. something like this should work:
namespace ELMFS
{
public class ReadFromCSV
{
public static List<TextSpeak> ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
return TxtSpk;
}
}
public class TextSpeak
{
public string Abreviated { get; private set; }
public string Expanded { get; private set; }
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
private void Display(int count)
{
textBox1.Text = "";
for (int i = 0; i <= count ; i++)
{
textBox1.Text += ((dataGridView1.Rows[i].Cells[1].Value).ToString()) + (dataGridView1.Rows[i].Cells[2].Value.ToString()) + Environment.NewLine;
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// your code here
string CSVFilePathName =Path.GetDirectoryName(Application.ExecutablePath).Replace(#"\bin\Debug", #"\NewFolder1\TEST.csv");
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
dataGridView1.DataSource = dt;
int count = 0;
if (dataGridView1.RowCount > 0)
{
count = dataGridView1.Rows.Count;
}
buttons = new Button[count];
for (int i = 0; i <count; i++)
{
buttons[i] = new Button();
buttons[i].Name = "buttons_Click" + i.ToString();
buttons[i].Text = "Click";
buttons[i].Click += new EventHandler(buttons_Click);
this.Controls.Add(buttons[i]);
buttons[i].Visible = false;
}
buttons[0].Visible = true;
// buttons[1].Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
}
private void buttons_Click(object sender, EventArgs e)
{
int count = dataGridView1.Rows.Count-1;
if(c <= count)
{
if (buttons[c].Name == "buttons_Click" + c.ToString())
{
buttons[c].Visible = false;
int j = c;
Display(j);
if (c != count)
{
c = c + 1;
buttons[c].Visible = true;
}
}
}
if (c == count)
{
buttons[0].Visible = true;
}
}
}
}
I'm not sure what is going on. I thought I had it set up to clear the output label at the end. Everytime I clear it, the program still remembers the previous number and adds to it. I honestly have no idea what is going on.
Also on a side note, how do I put set up radiobuttons to be used in the this method?
First coding class so i'm still kind of a beginner.
private double oilandlube()
{
if (checkBox1.Checked == true)
{
Oil_change = 26;
}
if (checkBox2.Checked == true)
{
Lube_job = 18;
}
return Oil_change + Lube_job;
}
private void Oiltype ()
{
if (radioButton1.Checked)
{
Regular = 0;
}
if (radioButton2.Checked)
{
Mixed = 10;
}
else
{
Mixed = 0;
}
if (radioButton3.Checked)
{
Full_Synthetic = 18;
}
else
{
Full_Synthetic = 0;
}
}
private void carwash()
{
if (radioButton4.Checked)
{
none = 0;
}
if (radioButton5.Checked)
{
complimentary = 0;
}
if (radioButton6.Checked)
{
Full_service = 6;
}
else
{
Full_service = 0;
}
if (radioButton7.Checked)
{
Premium = 9;
}
else
{
Premium = 0;
}
}
private double flushes()
{
if (checkBox3.Checked == true)
{
Radiator_flush = 30;
}
if (checkBox4.Checked == true)
{
Transmission_flush = 80;
}
return Radiator_flush + Transmission_flush;
}
private double misc()
{
if (checkBox5.Checked == true)
{
inspection = 15;
}
if (checkBox6.Checked == true)
{
replace_muffler = 100;
}
if (checkBox7.Checked == true)
{
tire_rotation = 20;
}
return inspection + replace_muffler;
}
private double partsandlabor()
{
double.TryParse(textBox1.Text, out parts);
double.TryParse(textBox2.Text, out labor);
return parts + labor;
}
private double tax()
{
return partsandlabor() * taxes;
}
private void summary()
{
service = oilandlube() + flushes() + misc();
total_parts = partsandlabor();
double total_tax = tax();
double grand_total = service + total_parts + total_tax;
label7.Text = service.ToString("c");
label8.Text = total_parts.ToString("c");
label9.Text = total_tax.ToString("c");
label10.Text = grand_total.ToString("c");
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
oilandlube();
carwash();
flushes();
misc();
partsandlabor();
summary();
}
private void ClearOilandlube()
{
checkBox1.Checked = false;
checkBox2.Checked = false;
}
private void ClearMisc()
{
checkBox5.Checked = false;
checkBox6.Checked = false;
checkBox7.Checked = false;
}
private void ClearFlushes()
{
checkBox3.Checked = false;
checkBox4.Checked = false;
}
private void ClearSummary()
{
label7.Text = "";
label8.Text = "";
label9.Text = "";
label10.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
ClearOilandlube();
ClearMisc();
ClearFlushes();
ClearSummary();
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton5.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
textBox1.Text = "0";
textBox2.Text = "0";
}
}
}
When you clear the contents of your controls, you should also clear the values of the backing variables, so they don't retain their previous values. You should be able to just set them back to zero in your Clear methods.
For example, oil and lube might look like:
private void ClearOilandlube()
{
checkBox1.Checked = false;
checkBox2.Checked = false;
Oil_change = 0;
Lube_job = 0;
Mixed = 0;
Regular = 0;
Full_Synthetic = 0;
}
It looks like you're holding state of some your variables globally so you can access them elsewhere.
Mixed = 10;
You'll have to reset that to some default value as well.
I am working with my C# Windows application, and this is my first time to use tdbgrid(component1). I want to prevent users from inputting duplicated values after validating them with the database.
Below is the code which I am using for it in (BeforeColUpdate)Event:
bool ExitValue = false;
private void C1TrueDBGrid_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)
{
if (e.Column.Name == "Groups Code")
{
for (int currentRow = 0; currentRow < this.C1TrueDBGrid.Rows.Count - 1;currentRow++)
{
string rowToCompare = this.C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.CellValue(currentRow).ToString();
for (int otherRow = currentRow+1 ; otherRow < this.C1TrueDBGrid.Rows.Count; otherRow++)
{
bool DuplicatedRow = true;
string Row = this.C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.CellValue(otherRow).ToString();
if (Row!=rowToCompare)
{
ExitValue = false;
break;
}
if (DuplicatedRow)
{
C1TrueDBGrid.Splits[0].DisplayColumns[tgdGroupsUsers.Col].DataColumn.Value = DBNull.Value;
MessageBox.Show("Sorry: but this item(s) is already Exists ", "Error Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
ExitValue = true;
e.Cancel = true;
}
}
}
}
else
{
//Clear Fields
C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.Value = null;
e.Cancel = true;
}
}
if not duplicated below is the code which I am using in (AfterColUpdate)Event:
private void C1TrueDBGrid_AfterColUpdate(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e)
{
if (!ExitValue)
{
int indexRow = this.C1TrueDBGrid.RowBookmark(this.C1TrueDBGrid.Row);
this.C1TrueDBGrid[indexRow, 0] = CSystemUsers.GroupsCode;
this.C1TrueDBGrid[indexRow, 0] = CSystemUsers.EngName;
}
}
componentone answer me the question:
private void c1TrueDBGrid1_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)
{
if (e.ColIndex == 1)
{
for (int i = 0; i < c1TrueDBGrid1.RowCount; i++)
{
if (c1TrueDBGrid1.Editor.Text == c1TrueDBGrid1[i, e.ColIndex].ToString())
{
MessageBox.Show("Sorry: but this item(s) already Exists", "Error Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
}
}
}
}
link:
http://our.componentone.com/groups/topic/how-do-i-prevent-duplicate-entries-in-c1truedbgrid/
hope this helps someone else in future: