Custom Datagridview Paging - c#

I am trying to make Datagridview paging, I have already performed the paging and it works fine, the problem is when I try to search for records from the database the problem is that Datagridview doesn't change and the data returned from the database is not showing and the pages count keeps increasing on each search.
Please take a look at this video :
https://www.youtube.com/watch?v=Ina0OlZagSo&ab_channel=RabeeQabaha
here is my Custom Datagridview class:
class GV_Paging : Guna.UI2.WinForms.Guna2DataGridView
{
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs = new BindingSource();
BindingList<DataTable> tables = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
DataTable dt = null;
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter)
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += Bs_PositionChanged;
Bs_PositionChanged(bs, EventArgs.Empty);
}
void Bs_PositionChanged(object sender, EventArgs e)
{
this.DataSource = tables[bs.Position];
}
}
and this is how I fill the data to Datagridview:
GV.PageSize = Convert.ToInt32(Math.Floor(Convert.ToDecimal(GV.Height / GV.RowTemplate.Height))) - 1;
DT = DBConn.ExecuteDataTable("select_all_materials", CommandType.StoredProcedure);
GV.SetPagedDataSource(DT, bindingNavigator1);
and here is the code for searching data from the database(work on text box text change):
GV.PageSize = Convert.ToInt32(Math.Floor(Convert.ToDecimal(GV.Height / GV.RowTemplate.Height))) - 1;
DT = DBConn.ExecuteDataTable("search_materials_by_name", CommandType.StoredProcedure, new
SqlParameter[] { new SqlParameter("#name", Material_name_txt.Text.Trim()) });
GV.SetPagedDataSource(DT, bindingNavigator1);

after working on it I was able to fix the problem, here is the working class:
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs;//= new BindingSource();
BindingList<DataTable> tables;// = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
if (dataTable == null || bnav == null)
{
return;
}
DataTable dt = null;
bs = new BindingSource();
tables = new BindingList<DataTable>();
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter)
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += Bs_PositionChanged;
Bs_PositionChanged(bs, EventArgs.Empty);
}
void Bs_PositionChanged(object sender, EventArgs e)
{
try
{
this.DataSource = tables[bs.Position];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

Why is nothing displaying in my listbox? C#

My program is supposed to take team names from an XML file and display them in the listbox, and when a team is selected from the listbox, players with a higher batting average on the team are displayed in a datagridview. For some reason nothing is showing up in my listbox, and therefore I cannot select anything and test if my program works.
public partial class Form1 : Form
{
DataSet resultset = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
resultset.ReadXml("Baseball.xml");
var myQuery = resultset.Tables[0].AsEnumerable().Select(row => new
{
teamname = row.Field<string>("Team")
})
.Distinct();
foreach (var rowname in myQuery)
{
listBox1.Items.Add(rowname.teamname.ToString());
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
double TotalhitsAverage, TotalatBatAverage, TeamAverage;
DataTable playerInformation = new DataTable();
DataRow[] tableName = resultset.Tables[0].Select("Team = '" + listBox1.SelectedItem + "'");
playerInformation = tableName.CopyToDataTable();
DataTable clonedcolumns = playerInformation.Clone();
clonedcolumns.Columns[3].DataType = typeof(double);
clonedcolumns.Columns[2].DataType = typeof(double);
foreach (DataRow row in playerInformation.Rows)
{
clonedcolumns.ImportRow(row);
}
TotalhitsAverage = clonedcolumns.AsEnumerable().Average(r => r.Field<double>("hits"));
TotalatBatAverage = clonedcolumns.AsEnumerable().Average(r => r.Field<double>("atBats"));
TeamAverage = TotalhitsAverage / TotalatBatAverage;
DataTable playerAverage = new DataTable();
DataRow rowPlayer = playerAverage.NewRow();
playerAverage.Columns.Add("Player", typeof(String));
playerAverage.Columns.Add("Batting Avg", typeof(double));
for (int i = 0; i < clonedcolumns.Rows.Count; i++)
{
double averageplayer = Convert.ToDouble(clonedcolumns.Rows[i][3]) / Convert.ToDouble(clonedcolumns.Rows[i][2]);
if (TeamAverage <= averageplayer)
{
playerAverage.Rows.Add(clonedcolumns.Rows[i][0].ToString(), Math.Round(averageplayer, 4));
}
}
DataView view = playerAverage.DefaultView;
view.Sort = "Batting Avg DESC";
DataTable sortedDate = view.ToTable();
dgvBaseball.DataSource = sortedDate;
dgvBaseball.AutoSize = true;
}
}

How to disable click of a column from a DataGridView?

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.

Delete the single selected row from a grid view at run time

I have a table having 2 columns viz ID and DETAILS.Data in a table is like
id=01 details="pritam=123 sourav=263" like this
i am working on a windows for application ..when the application will run the output comes what i am going to tell.. 1.in my application one combobox is there.when the application will run all the id will be bind in a combobox from the table. 2.when user will choose any id suddenly the details column data will be shown in a datagrid view in a splitted format like this.
NAME KEY
PRITAM 123
SOURAV 263
in this data grid view user can delete ant row by selecting the and click on the below delete button. insert any row by clickng the add new row button at the end ,modify any existing data and finally click on the update button and all the data are going to be stored in that data base like in previous format.. for that i have written the code in c# like this..
namespace windows_csharpp
{
public partial class Form5 : Form
{
SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da;
DataTable dt;
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
string sql="select EDIScheduleID from ETAProcessSchedule";
da= new SqlDataAdapter(sql, cc);
dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
ArrayList ls = new ArrayList();
int ss = 0;
int ss1 = 0;
int ssp = 1;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cc);
DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
string stp = dt.Rows[0][21].ToString();
string[] stp1 = stp.Split(' ');
List<Class1> lst = new List<Class1>();
ls.Clear();
for (int x = 0; x < stp1.Length; x++)
{
ls.Add(stp1[x].ToString());
}
for (int x = 0; x < ls.Count; x++)
{
string ssttt = ls[x].ToString();
string[] sssp = ssttt.Split('=');
for (int x1 = 1; x1 < sssp.Length; x1++)
{
ss = 0;
ss1 = ssp;
Class1 cs = new Class1()
{
Value = sssp[ss], Key= sssp[x1].ToString()
};
lst.Add(cs);
}
}
dataGridView1.DataSource = lst;
}
private void Update_Click(object sender, EventArgs e)
{
string value = null;
string keys = null;
string query = null;
string str = null;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
value = dataGridView1.Rows[i].Cells[0].Value.ToString();
keys = dataGridView1.Rows[i].Cells[1].Value.ToString();
string ss = value + '=' + keys;
str += ss + ' ';
}
query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'";
da = new SqlDataAdapter(query, cc);
dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Updated In Database Successfully");
}
and one class file is also there ..
class Class1
{
public string Value { get; set; }
public string Key { get; set; }
}
kindly help me in delete the selected row ,add the new row and update the all data in database like in previous format..
I think you already have working approach. If I understand right you need only two functions:
- Load Schedule details in the DataGridView (one key-value pair per row)
- Save edited/added/deleted key-value pairs to the database
Be sure next properties of DataGridView set to true:
this.YourDataGridView.AllowUserToAddRows = true;
this.YourDataGridView.AllowUserToDeleteRows = true;
And of course columns must be editable
In the methods was used const variables which was created in your Form (Form1)
private const string DETAILSDELIMITER = ' ';
private const string NAMEKEYDELIMITER = '=';
Method for loading schedule details in the DataGridView
//Use SqlParameters in the query,
//if not your application vulnerable for sql injection
private void LoadScheduleDetails(string scheduleID)
{
//You working only with one column, do not use '*' in SELECT statement if not nessesary
string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = #ScheduleID";
DataTable details = new DataTable();
//Get data from database
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection))
{
//Adding parameter
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
detailsCommand.Parameters.Add(id);
using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand ))
{
yourAdapter.Fill(details);
}
}
}
this.YourDataGridView.Rows.Clear();
if (details.Rows.Count > 0)
{
DataRow temp = details.Rows[0];
//get column by name.
string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER);
//Adding rows manually without DataSource
foreach(string pair in pairs)
{
this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER));
}
}
}
Method for saving data
I think better if you create columns already in the designer
Then you can access columns by it's name without hardcoding indexes
private void SaveDetails(string scheduleID)
{
StringBuilder details = new StringBuilder();
foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows)
{
string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString();
string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString();
//Here you can check if values are ok(not empty or something else)
//Create pair
details.Append(Form1.DETAILSDELIMITER);
details.Append(name);
details.Append(Form1.NAMEKEYDELIMITER);
details.Append(key);
}
//remove first space character
if (details.Length > 0)
details.Remove(0, 1);
//Save data to database
string query = "UPDATE ETAProcessSchedule SET ProcParameters=#Details WHERE EDIScheduleID=#ScheduleID";
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using (SqlCommand saveCommand = new SqlCommand(query, yourConnection))
{
//Adding parameters
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
SqlParameter procParams = new SqlParameter { ParameterName = "#Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() };
saveCommand.Parameters.Add(id);
saveCommand.Parameters.Add(procParams);
saveCommand.ExecuteNonQuery();
MessageBox.Show("Data Updated In Database Successfully");
}
}
}
Then use LoadScheduleDetails in the comboBox1_SelectedIndexChanged eventhandler
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.LoadScheduleDetails(scheduleID);
}
}
After data loaded, user can change it, add rows, delete rows
When user pressed "Update" button then use SaveDetails method,
where we collect data from all rows and update database with it
private void Update_Click(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.SaveDetails(scheduleID);
}
}
On your form load bind data:-
EDIT : -
private void Form5_Load(object sender, EventArgs e)
{
comboBox1.DataSource = loadddltable();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
public DataTable loadddl()
{
OleDbDataReader obj = null;
DataTable dt = new DataTable();
try
{
obj_dbconnection.CommandText = "Select * from TableName";
obj = obj_dbconnection.ExecuteReader();
if (obj != null)
{
if (obj.HasRows)
{
dt.Load(obj);
}
}
}
catch (Exception)
{
}
finally
{
if (obj != null)
{
obj.Close();
obj_dbconnection.Close();
}
}
return dt;
}
/*Code for Execute Reader*/
public OleDbDataReader ExecuteReader()
{
OleDbDataReader dr = null;
try
{
Open();
dr = cmd.ExecuteReader();
}
catch(Exception)
{ }
return dr;
}
/*Code for binding grid data*/
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue);
}
And then insert,edit,delete buttons as template fields to dataGridView and use dataGridView1_CellClick event to insert edit delete

datagridview not showing numbers from MS Access

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;
}

How to write code for next & previous button?

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

Categories