I am developing an online exam system project using ASP.NET (C#) & SQL Sever.
This is my code. I have a problem in implementing code for next & previous button. Please suggest me the answer. Thank you.
public partial class Default : Page
{
int count;
string ans;
int[] a=new int[5];
int t;
int ctr;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DateTime myDate;
DataTable dt = new DataTable();
DataRow dr;
public void Show()
{
Session["Answered"] = dt;
View v = this.View1;
Label l = default(Label);
l = (Label)v.FindControl("Label1");
l.Text = dt.Rows[ctr]["Serial"] + ".";
l = (Label)v.FindControl("Label2");
l.Text = dt.Rows[ctr]["question"].ToString();
RadioButtonList r = default(RadioButtonList);
r = (RadioButtonList)v.FindControl("RadioButtonList1");
r.Items.Clear();
r.Items.Add(dt.Rows[ctr]["choice1"].ToString());
r.Items.Add(dt.Rows[ctr]["choice2"].ToString());
r.Items.Add(dt.Rows[ctr]["choice3"].ToString());
r.Items.Add(dt.Rows[ctr]["choice4"].ToString());
r.SelectedIndex = Convert.ToInt32(dt.Rows[ctr]["selected"]);
Session["ctr"] = ctr;
}
protected void Timer1_Tick(object sender, System.EventArgs e)
{
DateTime mydate2 = DateTime.Now;
DateTime mydate3 = default(DateTime);
try
{
mydate3 = Convert.ToDateTime((myDate - mydate2).ToString());
this.Label5.Text = "Time Left: " + mydate3.ToShortTimeString();
}
catch (Exception ex)
{
this.Label5.Text = "Error Setting up the Timer. Contact Admin";
}
if (mydate3.ToShortTimeString() == "00:00:00")
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
DateTime myDate = new DateTime();
myDate =Convert.ToDateTime(Request.Cookies["start"].Value);
if (!IsPostBack) {
this.MultiView1.ActiveViewIndex = 0;
conn.Open();
cmd.Connection = conn;
Random arbit = new Random();
for (int i = 0; i <= a.GetUpperBound(0); i++) {
t = arbit.Next(1, 10);
if (Array.IndexOf(a, t) == -1) {
a[i] = t;
} else {
goto X;
}
}
for (int i = 0; i <= 4; i++)
{
cmd.CommandText = "select * from test where Serial=" + a[i];
da.SelectCommand = cmd;
da.Fill(ds, "test");
}
conn.Close();
dt = new DataTable("Answered");
dt.Columns.Add("Serial", typeof(int));
dt.Columns.Add("question", typeof(string));
dt.Columns.Add("choice1", typeof(string));
dt.Columns.Add("choice2", typeof(string));
dt.Columns.Add("choice3", typeof(string));
dt.Columns.Add("choice4", typeof(string));
dt.Columns.Add("correct", typeof(string));
dt.Columns.Add("selected", typeof(int));
DataRow r = null;
foreach (DataRow r_loopVariable in ds.Tables["test"].Rows) {
r = r_loopVariable;
dr = dt.NewRow();
dr["Serial"] = dt.Rows.Count + 1;
dr["question"] = r["question"];
dr["choice1"] = r["choice1"];
dr["choice2"] = r["choice2"];
dr["choice3"] = r["choice3"];
dr["choice4"] = r["choice4"];
dr["correct"] = r["correct"];
dr["selected"] = -1;
dt.Rows.Add(dr);
}
Session["Answered"] = dt;
Show();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
Session["ctr"] = ctr;
ctr += 1;
Show();
if (ctr == 4)
{
this.btnNext.Enabled = false;
}
this.btnPrev.Enabled = true;
}
protected void btnPrev_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
ctr = ctr - 1;
if (ctr == 0)
{
this.btnPrev.Enabled = false;
}
Session["ctr"] = ctr;
this.btnNext.Enabled = true;
Show();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
Session["Answered"] = dt;
}
protected void btnShowMarks_Click(object sender, EventArgs e)
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
Session["marks"] = dt;
int []b=new int[6];
foreach (int c in b)
{
RadioButtonList1.SelectedIndex.ToString();
}
}
}
I would suggest you to use the Wizard control.
Here are some examples:
http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
http://www.codeproject.com/KB/aspnet/Wizard_Control.aspx
Since you seem to develop a wizard-like form did you consider using the Wizard control.
You can Fetch random data from DB and store it in a dataset. Then there you can get questions in usual manner. Then you can fetch questions using a variable which will store the question number to get previous and next questions. If user clicks on Previous then variable - 1 also +1 if next
Related
Adding data in datatable from dropdown and displaying it in gridview. Then I am deleting a row and maintaining the ViewState but after deleting one row and mapping my values again I get the earlier state of the table in the gridview with duplicated records.
Here's the code:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
//dt = new DataTable("tblTest");
//dt = ViewState["updatedtbl"] as DataTable;
DataColumn dc1 = new DataColumn();
dc1.DataType = typeof(String);
dc1.ColumnName = "A";
DataColumn dc2 = new DataColumn();
dc2.DataType = typeof(String);
dc2.ColumnName = "B";
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
//ViewState["dt"] = dt;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable();
DropDownList1.Items.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName));
}
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["A"] += DropDownList1.SelectedItem.Value + "|";
Session["B"] += DropDownList2.SelectedItem.Value + "|";
CreateTable();
}
public void CreateTable()
{
string[] sa = Session["A"].ToString().Split('|');
string[] sb = Session["B"].ToString().Split('|');
int recordnum = sa.Length;
for (int j = 0; j < recordnum - 1; j++)
{
DataRow dr = dt.NewRow();
dr["A"] = sa[j].ToString();
dr["B"] = sb[j].ToString();
dt.Rows.Add(dr);
}
ViewState["tbl"] = dt;
BindGrid();
}
protected void BindGrid()
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dx = ViewState["tbl"] as DataTable;
//DataTable dx = dt;
if (dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
ViewState["updatedtbl"] = dx;
}
else //To check which portion of code is being executed
{
Label1.Text = "Deleted";
Label2.Text = dx.Rows.Count.ToString();
}
}
In delete event you are reassigning the updated datatable to different viewstate with name updatedtbl. You should assign it to ViewState["tbl"].
if(dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
//ViewState["updatedtbl"] = dx; <<---- pay attention here
ViewState["tbl"] = dx; <<---- pay attention here
}
I have a DataGridView on WindowsForm where I'm passing data from my database. The purpose of this DataGridView is to enable to user to click on a value and modify it. However, I don't want the user to leave the value blank, add words, only numbers.. and of course not change the Id, which is the primary key of my table.
I'm trying to achieve this by disabling the column which host the id of the table, however I don't know how to tell that column to disable editing.
Here is my code:
public partial class eraseGrade : Form
{
Conexion con;
String rut;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder scb;
public eraseGrade()
{
InitializeComponent();
cbxAsig.Enabled = false;
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
private void btnBuscar_Click_1(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
rut = txtRut.Text.Trim();
if (validarTXTVacios(txtRut))
{
MessageBox.Show("Add a Rut, please");
}
else
{
Alumno a = new Alumno(rut);
a.buscar(a);
cbxAsig.Items.Clear();
if (a.Nombre != null)
{
lblNombre.Text = a.Nombre + " " + a.Apellido;
cbxAsig.Enabled = true;
AsignaturaAlumno b = new AsignaturaAlumno();
List<AsignaturaAlumno> l = b.buscarTodosByAlumno(rut);
List<String> codigosAsig = new List<string>();
if (l.Count != 0)
{
for (int i = 0; i < l.Count(); i++)
{
codigosAsig.Add(l.ElementAt(i).Cod_asig.ToString());
}
Asignatura asigT = new Asignatura();
List<Asignatura> asig = new List<Asignatura>();
for (int i = 0; i < codigosAsig.Count(); i++)
{
asig.Add(asigT.buscarbyCod(codigosAsig.ElementAt(i).ToString()));
}
for (int i = 0; i < asig.Count(); i++)
{
cbxAsig.Items.Add(asig.ElementAt(i).CodAsignatura);
}
cbxAsig.Enabled = true;
btnNotas.Enabled = true;
}
}
else
{
lblNombre.Text = "";
MessageBox.Show("Alumno no encontrado");
lblAsig.Text = "";
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
}
}
private void cbxAsig_SelectedIndexChanged(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
Asignatura asignatura = new Asignatura();
Asignatura l = asignatura.buscarbyCod(cbxAsig.SelectedItem.ToString());
lblAsig.Text = l.Nombre + " (" + l.IdSeccion + ")";
}
Here is the code that obtains data from the database and inserts it into the DataGridView.
private void btnNotas_Click(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
if (cbxAsig.SelectedItem != null)
{
String codigo = cbxAsig.SelectedItem.ToString();
sda = new SqlDataAdapter(#"SELECT id, num_eval AS Evaluacion, porcentaje AS Porcentaje, nota AS Nota FROM registro WHERE rut = #rut AND cod_asig = #cod_asig", con.Con);
sda.SelectCommand.Parameters.AddWithValue("#rut", rut);
sda.SelectCommand.Parameters.AddWithValue("#cod_asig", codigo);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
btnBorra.Enabled = true;
}
else
{
MessageBox.Show("Seleccione una asignatura");
}
}
public Boolean validarTXTVacios(TextBox r)
{
if (txtRut.Text.Equals(""))
{
return true;
}
return false;
}
Here is the button that updates the table with the new data from the columns. It doesn't respect primary keys or data types.
private void btnBorra_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
Just set that column's ReadOnly to true like this:
dataGridView1.Columns[0].ReadOnly = true;
You should change 0 to the id's column index.
EDIT: To validate a column to be for example int you could do like this:
dataGridView1.Columns[0].ReadOnly = true;
dataGridView1.AllowUserToAddRows = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int x;
if (int.TryParse(row.Cells[1].Value.ToString(), out x))
{
MessageBox.Show("Valid");
}
}
You can achieve this by setting Row.Cells[cellIndex].Enabled = false; during GridView RowDataBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellIndex].Enabled = false;
}
}
Alter cellIndex to your actual id cell index.
I have created a web application in that I have a drop down list and a Gridview. I fill drop down value from DB and I need to display data in grid view for the selected value but data from another table . I don't no how to do this can any one help me please.My code is below. Thanks in advance.
Code behind
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
dropDownData.DataSource = dt;
dropDownData.DataTextField = "Work_Packages";
dropDownData.DataValueField = "Work_Packages";
dropDownData.DataBind();
Bind_Gridview();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + ex.Message + "');</script>", false);
}
}
public void Displaysearchresult(string strSearch)
{
SqlCommand cmd = new SqlCommand("Select * from ArR_Station_Work_Packages Where Station_Name like'" + txtstationName.Text + "%'", myConnection);
cmd.Parameters.AddWithValue("#Work_Packages", strSearch);
cmd.Connection.Open();
dropDownData.DataSource = cmd.ExecuteReader();
dropDownData.DataTextField = "Work_Packages";
dropDownData.DataValueField = "Work_Packages";
dropDownData.DataBind();
}
protected void GetWorkPackages(object sender, EventArgs e)
{
if (txtstationName.Text == "" | txtstationName.Text == null)
{
}
else
{
Displaysearchresult(txtstationName.Text);
}
}
protected void ddlSelectedData(object sender, EventArgs e)
{
Bind_Gridview();
}
private void Bind_Gridview()
{
SqlCommand cmd = new SqlCommand("Select * from ArR_WP_BOQ_Details Where BOQ_ID like'" + dropDownData.SelectedValue + "'", myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
dt.Clear();
da.Fill(dt);
myConnection.Close();
ViewState["BOQ"] = null;
ViewState["BOQ"] = (DataTable)dt;
addnewrow();
grd_BOQ.DataSource = dt;
grd_BOQ.DataBind();
}
private void addnewrow()
{
if (ViewState["BOQ"] != null)
{
DataTable idt = (DataTable)ViewState["BOQ"];
DataRow drCurrentRow = null;
DataRow drCurrentRow_lastrow = null;
int New_gridrowcount = idt.Rows.Count;
drCurrentRow = idt.NewRow();
drCurrentRow_lastrow = idt.NewRow();
if (idt.Rows.Count >= 10)
{
idt.Rows.InsertAt(drCurrentRow, 9);
idt.Rows.InsertAt(drCurrentRow_lastrow, idt.Rows.Count);
}
else
{
idt.Rows.Add(drCurrentRow);
}
ViewState["BOQ"] = idt;
}
}
protected void grd_BOQ_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
Bind_Gridview();
grd_BOQ.PageIndex = e.NewPageIndex;
grd_BOQ.EditIndex = -1;
grd_BOQ.DataBind();
}
protected void grd_BOQ_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
int grd_lastpgcount = grd_BOQ.PageIndex;
dt = (DataTable)ViewState["BOQ"];
int count = dt.Rows.Count;
if (e.Row.RowType == DataControlRowType.DataRow || !string.IsNullOrEmpty(dropDownData.SelectedValue))
{
int rowcreate_rowindex = e.Row.RowIndex;
if (rowcreate_rowindex < count - 1 && rowcreate_rowindex != 9 && grd_lastpgcount * 10 + rowcreate_rowindex + 1 < count)
{
for (int rc = 0; rc < 1; rc++)
{
edit_button = new ImageButton();
edit_button.ID = "edit_button";
edit_button.ImageUrl = "~/images/edit.png";
edit_button.Style.Add("width", "20px");
edit_button.Style.Add("height", "20px");
edit_button.CommandName = "Edit";
edit_button.ToolTip = "Edit";
e.Row.Cells[rc].Controls.Add(edit_button);
update_button = new ImageButton();
update_button.ID = "update_button";
update_button.ImageUrl = "~/images/save.png";
update_button.Style.Add("width", "20px");
update_button.Style.Add("height", "20px");
update_button.CommandName = "Update";
update_button.ToolTip = "Update";
e.Row.Cells[rc].Controls.Add(update_button);
if (onrow_edit_flag == rowcreate_rowindex)
{
edit_button.Visible = false;
update_button.Visible = true;
}
else
{
edit_button.Visible = true;
update_button.Visible = false;
}
}
}
else if (rowcreate_rowindex == count - 1 || rowcreate_rowindex == 9 || grd_lastpgcount * 10 + rowcreate_rowindex + 1 == count)
{
for (int rc = 0; rc < 1; rc++)
{
add_button = new ImageButton();
add_button.ID = "add_button";
add_button.ImageUrl = "~/images/Add.png";
add_button.Style.Add("width", "20px");
add_button.Style.Add("height", "20px");
add_button.Click += new ImageClickEventHandler(insert_button_Click);
add_button.ToolTip = "Add";
e.Row.Cells[rc].Controls.Add(add_button);
update_button = new ImageButton();
update_button.ID = "update_button";
update_button.ImageUrl = "~/images/save.png";
update_button.Style.Add("width", "20px");
update_button.Style.Add("height", "20px");
update_button.Click += new ImageClickEventHandler(insert_save_click);
update_button.ToolTip = "Add";
e.Row.Cells[rc].Controls.Add(update_button);
if (onrow_create_flag == rowcreate_rowindex || dt.Rows.Count % grd_BOQ.PageSize == onrow_create_flag)
{
add_button.Visible = false;
update_button.Visible = true;
}
else
{
add_button.Visible = true;
update_button.Visible = false;
}
}
}
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + msg + "');</script>", false);
}
}
At this line of code dr = dt.Rows[k]; I am getting the exception Object reference not set to an instance of an object. where I am going wrong?
public partial class EditEngClgList : Form
{
public EditEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
MessageBox.Show("Error:" + err);
}
string sql = "Select * From EngColeges order by EngClgID";
da = new OleDbDataAdapter(sql, acccon);
cmdb = new OleDbCommandBuilder(da);
dt1 = new DataTable();
da.Fill(dt1);
bs = new BindingSource();
bs.DataSource = dt1;
dataGridView1.DataSource = bs;
dataGridView1.Columns[1].Visible = false;
}
private void button4_Click(object sender, EventArgs e)
{
List<int> checkedclg = new List<int>();
DataRow dr;
List<int> checkedclgid = new List<int>();
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
}
foreach (int k in checkedclg)
{
dr = dt.Rows[k]; //this datatable object I hae created in another function
dt.Rows[k].Delete();
foreach (int j in checkedclgid)
{
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
oleDbCommand.Parameters.Add("#clgID", OleDbType.Integer).Value = j;
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
}
}
}
Thanks for any help
Place a breakpoint on that line - most likely the dt object is null.
To address the comment that k may be larger than Rows.Count, I would think if the problem was with k, you'd get an exception indicating the index is out of bounds (IndexOutOfBoundsException).
I have a datagrid view and it's datasource is MS Access(which have a datatype, currency, date/time, and numbers), It shows data in the database but doesn't show other data types, only words or any string, here is my code for adding rows
string[] rowData = new string[columnCount];
while (dr.Read())
{
for (int k = 0; k < columnCount; k++)
{
if (dr.GetFieldType(k).ToString() == "System.int32")
{
rowData[k] = dr.GetInt32(k).ToString();
}
if (dr.GetFieldType(k).ToString() == "System.String")
{
rowData[k] = dr.GetString(k);
}
}
dataGridView1.Rows.Add(rowData);
}
can you help me with this? thanks
Instead of using the code above, I use this code, and it works
private void Form6_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new OleDbConnectionStringBuilder();
str.Provider = "Microsoft.ace.Oledb.12.0";
str.DataSource = #"\\sisc-erelim\4_Printing\VTDB\DB\VirginiTEADB2.accdb";
con = new OleDbConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from Accountstbl");
dataGridView1.Columns["Password"].Visible = false;
dataGridView1.Columns["Picture"].Visible = false;
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}