How to retrieve data from DataTable by iterating through the rows - c#

I want to put this into a loop, the code is working fine
but I can't make a loop for it.
When it detects a new data on a table it will automatically add
another item, on my code below it only shows two user controls but I need to generate all of the value in the table.
Here is the code
public partial class Form1 : Form
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=rmsdb;username=root;password=");
MySqlCommand command;
MySqlDataAdapter da;
public Form1()
{
InitializeComponent();
LRNincrement();
}
int poss = 10;
public void AddItems(string Text, bool Checked)
{
DynaItems item = new DynamicUserControl.DynaItems(Text, Checked);
PanelContainer.Controls.Add(item);
item.Top = poss;
poss = (item.Top + item.Height + 10);
}
private void additembtn_Click(object sender, EventArgs e)
{
LRNincrement();
txt.Text = "";
}
private void LRNincrement()
{
String selectQuery = "SELECT lrnnumber from rmsdb.studentstable";
command = new MySqlCommand(selectQuery, connection);
da = new MySqlDataAdapter(command);
DataTable table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 0)
{
string trylol = table.Rows[0][0].ToString();
AddItems(trylol, true);
}
if (table.Rows.Count > 1)
{
string trylol1 = table.Rows[1][0].ToString();
AddItems(trylol1, true);
}
}
}

Replace the below the code
{
string trylol = table.Rows[0][0].ToString();
AddItems(trylol, true);
}
if (table.Rows.Count > 1)
{
string trylol1 = table.Rows[1][0].ToString();
AddItems(trylol1, true);
}
with
string itemName = string.Empty;
for(int i = 0; i< table.Rows.Count; i++)
{
itemName = table.Rows[i][0].ToString();
AddItems(itemName, true);
}
I am not able to test this code. But hope this help you to find the solution.

Related

survey page in asp c#

I have requirement to create a survey web form which should be loaded from database.
Each questions will have 10 rating items from 1-10 and the result should be saved to the database with question number.
I tried to achieve it with a web form with label control at the top and RadioButtonList for options, but only one question and answer is possible to load for display at a time. I'm new to web programming. If there is any working code sample or any idea how to achieve this, it would be helpful.
I've done the coding to put each question on page and on button click I am loading the next question, but I need all the questions on a single page.
public partial class _Default : System.Web.UI.Page
{
public static SqlConnection sqlconn;
protected string PostBackStr;
protected void Page_Load(object sender, EventArgs e)
{
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "time");
if (IsPostBack)
{
string eventArg = Request["__EVENTARGUMENT"];
if (eventArg == "time")
{
string str = "select * from tbl_Question";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Visible = false;
txtName.Visible =false;
Button1.Visible = false;
Panel1.Visible = true;
lblName.Text = "Name : " + txtName.Text;
int score = Convert.ToInt32(txtScore.Text);
lblScore.Text = "Score : " + Convert.ToString(score);
Session["counter"]="1";
Random rnd = new Random();
int i = rnd.Next(1, 10);//Here specify your starting slno of question table and ending no.
//lblQuestion.Text = i.ToString();
getQuestion(i);
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "select * from tbl_Question ";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
int count = ds2.Tables[0].Rows.Count;
getNextQuestion(count);
}
public void getQuestion(int no)
{
string str = "select * from tbl_Question where slNo=" + no + "";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "Question");
// int count = ds2.Tables[0].Rows.Count;
if (ds2.Tables[0].Rows.Count > 0)
{
DataRow dtr;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
dtr = ds2.Tables[0].Rows[i];
Session["Answer"] = Convert.ToString(Convert.ToInt32 (dtr["Correct"].ToString())-1);
lblQuestion.Text = "Q." + Session["counter"].ToString() + " " + dtr["Question"].ToString();
lblQuestion2.Text = "Q." + Session["counter"].ToString() + " " + dtr["arQuestion"].ToString();
LblQNNo.Text = Session["counter"].ToString();
RblOption.ClearSelection();
RblOption.Items.Clear();
RblOption.Items.Add(dtr["Option1"].ToString());
RblOption.Items.Add(dtr["Option2"].ToString());
RblOption.Items.Add(dtr["Option3"].ToString());
RblOption.Items.Add(dtr["Option4"].ToString());
RblOption.Items.Add(dtr["Option5"].ToString());
RblOption.Items.Add(dtr["Option6"].ToString());
RblOption.Items.Add(dtr["Option7"].ToString());
RblOption.Items.Add(dtr["Option8"].ToString());
RblOption.Items.Add(dtr["Option9"].ToString());
RblOption.Items.Add(dtr["Option10"].ToString());
i++;
}
}
}
public void getNextQuestion(int cnt)
{
if (Convert.ToInt32(Session["counter"].ToString()) < cnt)
{
Random rnd = new Random();
int i = rnd.Next(1, 10);
lblQuestion.Text = i.ToString();
getQuestion(i);
//qst_no = i;
Session["counter"] = Convert.ToString(Convert.ToInt32(Session["counter"].ToString()) + 1);
}
else
{
Panel2.Visible = false;
//code for displaying after completting the exam, if you want to show the result then you can code here.
}
}
protected void Button3_Click(object sender, EventArgs e)
{
insertAns();
}
private void insertAns()
{
SqlCommand cmd;
sqlconn = new SqlConnection(ConfigurationManager.AppSettings["sqlconnstr"].ToString());
cmd = new SqlCommand("insert into Tbl_Ans(UserID, Question_ID, Answer) values(#ans, #ans1, #ans2)", sqlconn);
cmd.Parameters.AddWithValue("#ans", txtName.Text);
cmd.Parameters.AddWithValue("#ans1", Session["counter"].ToString());
cmd.Parameters.AddWithValue("#ans2", RblOption.SelectedItem.Text);
sqlconn.Open();
int i = cmd.ExecuteNonQuery();
sqlconn.Close();
if (i != 0)
{
lbmsg.Text = "Your Answer Submitted Succesfully";
lbmsg.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
lbmsg.Text = "Some Problem Occured";
lbmsg.ForeColor = System.Drawing.Color.Red;
}
}
#region Connection Open
public void ConnectionOpen()
{
try
{
if (sqlconn.State == ConnectionState.Closed) { sqlconn.Open(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException sex)
{
lbmsg.Text = sex.Message;
}
}
#endregion
#region Connection Close
public void ConnectionClose()
{
try
{
if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); }
}
catch (SqlException ex)
{
lbmsg.Text = ex.Message;
}
catch (SystemException exs)
{
lbmsg.Text = exs.Message;
}
}
#endregion
}
first i want to say that you should use question table id instead of question number to save with the answer for future use.
I dont know more about dotnet so i have not attached any code here. But i can suggest you that
First fetch all the questions with their respective id into an object or array or fetch from them adaptor etc.
Then you can use a form to show them using foreach loop. for eg.
suppose "questions" is an array containing your all fetched questions from database. then apply
<form action="abc" method="post">
foreach(questions as question){
<tr>
<td>(print your question here)</td>
<td><input type="anything you want" name="(print here question.id)" />
</tr>
}
<input type="submit" value="submit" />
</form>
Now where you will fetch data on the form submission then you can easily access the answers with their name that is already question id. So now both have associated with each other.
welcome for any query if not clear.

C# - Populating a List with data from a database

I have a List (listOfQuestionIDs) stored in ViewState of 10 different numbers and an int counter (questionCounter) stored in ViewState which I intend to use to access the different numbers in the first list.
However, as I increment the value of ViewState["questionCounter"] by 1 the contents of listOfAnswerIDs and listOfAnswers remain exactly the same in the code below. Why is this?
protected void getAnswers()
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
List<int> listOfQuestionIDs = (List<int>)(ViewState["listOfQuestionIDs"]);
int questionCounter = Convert.ToInt32(ViewState["questionCounter"]);
List<string> listOfAnswerIDs = new List<string>();
List<string> listOfAnswers = new List<string>();
List<string> listOfCorrectAnswerIDs = new List<string>();
try
{
conn.Open();
string cmdText = "SELECT * FROM answers WHERE question_id=#QuestionID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmd.Parameters["#QuestionID"].Value = Convert.ToInt32(listOfQuestionIDs[questionCounter]);
reader = cmd.ExecuteReader();
while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
if (reader["correct"].ToString().Equals("Y"))
{
listOfCorrectAnswerIDs.Add(reader["answer_id"].ToString());
}
}
for (int i = 0; i < listOfAnswerIDs.Count; i++)
{
lblTitle.Text += listOfAnswerIDs[i].ToString();
}
reader.Close();
populateAnswers(listOfAnswerIDs.Count, listOfAnswers, listOfAnswerIDs);
}
catch
{
lblError.Text = "Database connection error - failed to read records.";
}
finally
{
conn.Close();
}
ViewState["listOfQuestionIDs"] = listOfQuestionIDs;
ViewState["listOfCorrectAnswerIDs"] = listOfCorrectAnswerIDs;
}
Here's where I increment the questionCounter:
protected void btnNext_Click(object sender, EventArgs e)
{
.........
getNextQuestion();
}
protected void getNextQuestion()
{
int questionCounter = Convert.ToInt32(ViewState["QuestionCounter"]);
..........
getAnswers();
................
questionCounter += 1;
ViewState["QuestionCounter"] = questionCounter;
}
ViewState keys are case sensitive. In getAnswers() you use "questionCounter" and in getNextQuestion() you use "QuestionCounter". Pick one and keep it consistent.

Postback vs Button_Click

I have problem with button click event and post back. I have a page with some textboxes and some drop-down lists. I fill those textboxes and ddls from database. I also have 2 buttons. One of them is updating database with changed data from textboxes and drop-down lists. Second button is displaying additional data depending on value from one of the drop-down list. My problem is that when I click update button the database is updated and data in textboxes and ddls are changed but when I enter into address tab and push Enter I got old data (In database everything is changed into new values). I could add method to
if (IsPostBack)
and data will be always fresh but in that case I will not be able to change value in one of the drop down list which displays additional data (Auto post back will load data into this ddl). Is there any workaround to this? If my description is not clear, please let me know.
EDIT1 Adding C# code
public partial class EditStaff : System.Web.UI.Page
{
Methods methods = new Methods();
IPrincipal p = HttpContext.Current.User;
protected void Page_Load(object sender, EventArgs e)
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
if (!IsPostBack)
{
GetDDLsItems();
FillFields();
}
else
{
//FillFields();
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string update_error = "";
string SOEID = txtSOEID.Text;
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
string email = txtEmail.Text.Trim();
int remsCode = Convert.ToInt32(ddlREMS.SelectedItem.ToString());
int active = Convert.ToInt32(ddlActive.SelectedValue);
int isGVO = Convert.ToInt32(ddlIsGVO.SelectedValue);
int gvoTeamID = Convert.ToInt32(ddlGVOTeams.SelectedValue);
int profileID = Convert.ToInt32(ddlProfiles.SelectedValue);
int isSOW = Convert.ToInt16(ddlIsSOW.SelectedValue);
int headcount = Convert.ToInt32(ddlHeadcount.SelectedValue);
string updater_domain = p.Identity.Name.ToString();
string updater = "";
int index = updater_domain.IndexOf("\\");
int email_at_index = email.IndexOf("#");
if (index != -1)
{
updater = updater_domain.Substring(index + 1, 7);
}
else
{
updater = updater_domain;
}
if (firstName.Length < 2)
{
update_error = "First Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (lastName.Length < 2)
{
update_error = update_error + "Last Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (email_at_index == -1 && email.Length < 5)
{
update_error = update_error + "Invalid email address.";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(13);
dbManager.AddParameters(0, "#SOEID", SOEID);
dbManager.AddParameters(1, "#firstName", firstName);
dbManager.AddParameters(2, "#LastName", lastName);
dbManager.AddParameters(3, "#Email", email);
dbManager.AddParameters(4, "#REMSCode", remsCode);
dbManager.AddParameters(5, "#Active", active);
dbManager.AddParameters(6, "#IsGVO", isGVO);
dbManager.AddParameters(7, "#gvoTeamID", gvoTeamID);
dbManager.AddParameters(8, "#profileID", profileID);
dbManager.AddParameters(9, "#isSOW", isSOW);
dbManager.AddParameters(10, "#headcount", headcount);
dbManager.AddParameters(11, "#lastUpdatedBy", updater);
dbManager.AddParameters(12, "#status", active);
dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "sp_update_user");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
lblStatus.Visible = true;
lblStatus.Text = "User data updated successfully.";
lblStatus.ForeColor = System.Drawing.Color.Green;
FillFields();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
FillFields();
gvREMSDetails.Visible = false;
}
private void FillFields()
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
dsUserDetails = GetUserDetails(soeid);
dtUserDetails = dsUserDetails.Tables[0];
string gvoTeam = dtUserDetails.Rows[0].ItemArray[8].ToString();
string profile = dtUserDetails.Rows[0].ItemArray[10].ToString();
string remsCode = dtUserDetails.Rows[0].ItemArray[4].ToString();
txtSOEID.Text = dtUserDetails.Rows[0].ItemArray[0].ToString();
txtFirstName.Text = dtUserDetails.Rows[0].ItemArray[1].ToString();
txtLastName.Text = dtUserDetails.Rows[0].ItemArray[2].ToString();
txtEmail.Text = dtUserDetails.Rows[0].ItemArray[3].ToString();
ddlREMS.SelectedValue = remsCode.ToString();
txtAddress.Text = dtUserDetails.Rows[0].ItemArray[5].ToString();
//Response.Write((Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString());
ddlActive.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString();
ddlIsGVO.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[7])).ToString();
ddlGVOTeams.SelectedValue = gvoTeam;
ddlProfiles.SelectedValue = profile;
ddlIsSOW.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[12])).ToString();
lblLastUpdatedBy_value.Text = dtUserDetails.Rows[0].ItemArray[14].ToString();
lblLastUpdatedDate_value.Text = dtUserDetails.Rows[0].ItemArray[15].ToString();
}
protected void btnGetREMSdetails_Click(object sender, EventArgs e)
{
//int remsCode = Convert.ToInt32(ddlREMS.SelectedValue);
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#remscode", Convert.ToInt32(ddlREMS.SelectedValue));
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwREMSDetails where [rems code] = #remscode");
gvREMSDetails.DataSource = ds;
gvREMSDetails.DataBind();
gvREMSDetails.Visible = true;
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
private static DataSet GetUserDetails(string soeid)
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#soeid", soeid);
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwUsersDetails where soeid = #soeid");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
return ds;
}
private void GetDDLsItems()
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "sp_select_edit_user_ddls");
ddlREMS.DataSource = ds.Tables[0];
ddlREMS.DataTextField = "remsCode";
ddlREMS.DataValueField = "remsCode";
ddlREMS.DataBind();
ddlActive.DataSource = ds.Tables[1];
ddlActive.DataTextField = "Active";
ddlActive.DataValueField = "ActiveID";
ddlActive.DataBind();
ddlIsGVO.DataSource = ds.Tables[2];
ddlIsGVO.DataTextField = "IsGVO";
ddlIsGVO.DataValueField = "IsGVOID";
ddlIsGVO.DataBind();
//methods.GetGVOFunctions(ddlGVOFunctions);
//int? gvoFunctionID = string.IsNullOrEmpty(ddlGVOFunctions.SelectedValue) ? (int?)null : (int?)Convert.ToInt32(ddlGVOFunctions.SelectedValue);
methods.GetGVOTeams(null, ddlGVOTeams);
ddlProfiles.DataSource = ds.Tables[3];
ddlProfiles.DataTextField = "profilename";
ddlProfiles.DataValueField = "profileID";
ddlProfiles.DataBind();
ddlIsSOW.DataSource = ds.Tables[4];
ddlIsSOW.DataTextField = "IsSOW";
ddlIsSOW.DataValueField = "IsSOWID";
ddlIsSOW.DataBind();
ddlHeadcount.DataSource = ds.Tables[5];
ddlHeadcount.DataTextField = "Headcount";
ddlHeadcount.DataValueField = "HeadcountID";
ddlHeadcount.DataBind();
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
}
I'm not 100% I completly understand the issue, but it sounds to me that you need to have
if(!IsPostBack)
{
// load dropdown data here
}
where you load all your data into the dropdowns, and then on the dropdown have
<asp:DropDownList SelectedIndexChanged="ddlDropdown_SelectedIndexChanged" id="ddlDropdown" AutoPostBack="true"></asp:DropDownList>
Then in your code behind have
protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
}

Generic list not being populated by db

I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}

How can we do pagination in datagridview in winform

I want to show 10 records per page in a datagridview on a window form and user must click next button to show next 10 records. Is it there some property in DataGridview or do i need to create a custom control.
What i need to do to achieve this.
Here's a simple working example, where a
BindingNavigator GUI control uses a
BindingSource object to
identify page breaks, by setting its DataSource to a custom subclass of IListSource.
(Thanks to this answer for
the key idea.) When the user clicks the "next page" button, the BindingNavigator fires bindingSource1_CurrentChanged and your code can fetch the desired records. Instructions:
Create a Windows Forms application
Drag onto the form a BindingNavigator, a DataGridView, and a BindingSource
Replace Form1.cs with the following code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PagedDataGridView
{
public partial class Form1 : Form
{
private const int totalRecords = 43;
private const int pageSize = 10;
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Index" });
bindingNavigator1.BindingSource = bindingSource1;
bindingSource1.CurrentChanged += new System.EventHandler(bindingSource1_CurrentChanged);
bindingSource1.DataSource = new PageOffsetList();
}
private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
// The desired page has changed, so fetch the page of records using the "Current" offset
int offset = (int)bindingSource1.Current;
var records = new List<Record>();
for (int i = offset; i < offset + pageSize && i < totalRecords; i++)
records.Add(new Record { Index = i });
dataGridView1.DataSource = records;
}
class Record
{
public int Index { get; set; }
}
class PageOffsetList : System.ComponentModel.IListSource
{
public bool ContainsListCollection { get; protected set; }
public System.Collections.IList GetList()
{
// Return a list of page offsets based on "totalRecords" and "pageSize"
var pageOffsets = new List<int>();
for (int offset = 0; offset < totalRecords; offset += pageSize)
pageOffsets.Add(offset);
return pageOffsets;
}
}
}
}
Here is my solution : It took me almost a year to find it and proud of this one
public class SuperGrid : DataGridView
{
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];
}
}
How to use it? Add above code to your project, drag the Supergrid and a bindingnavigator control to your win form .
superGrid1.PageSize = 5;
DataTable dt = DataProvider.ExecuteDt("select * from test order by col");
superGrid1.SetPagedDataSource(dt, bindingNavigator1);
And you get a paged Datagridview with data binding without much hastle/
Implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net, this is another solution :
https://www.aspsnippets.com/Articles/Implement-Paging-DataGridView-in-Windows-Forms-WinForms-Application-using-C-and-VBNet.aspx
In this article It will be explained how to implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net.
DataGridView control in Windows Forms (WinForms) Application does not have paging capabilities and hence Custom Paging using Stored Procedure needs to be implemented.
The Stored Procedure accepts PageIndex and PageSize as input parameters in order to fetch the records for the desired page index. In order to populate the Pager in front end, the total number of records in the table is needed which is fetched using the RecordCount Output parameter.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE PROCEDURE [dbo].[GetCustomersPageWise]
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [CustomerID] ASC
)AS RowNumber
,[CustomerID]
,[ContactName]
,[Country]
INTO #Results
FROM [Customers]
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT [CustomerID]
,[ContactName]
,[Country]
FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Initially the value of the PageSize is set to 5 and the PageIndex is set as 1. The value of the RecordCount Output parameter and PageIndex are passed to the PopulatePager method (discussed later).
C#
//Set the Page Size.
int PageSize = 5;
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid(1);
}
private void BindGrid(int pageIndex)
{
string constring = #"Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetCustomersPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
Each dynamic Button is assigned a click event handler, when the Button is clicked the value of its Name is passed as PageIndex parameter to the BindGrid function, which populates the DataGridView with the new set of records.
C#
private void PopulatePager(int recordCount, int currentPage)
{
List<Page> pages = new List<Page>();
int startIndex, endIndex;
int pagerSpan = 5;
//Calculate the Start and End Index of pages to be displayed.
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
startIndex = currentPage > 1 && currentPage + pagerSpan - 1 < pagerSpan ? currentPage : 1;
endIndex = pageCount > pagerSpan ? pagerSpan : pageCount;
if (currentPage > pagerSpan % 2)
{
if (currentPage == 2)
{
endIndex = 5;
}
else
{
endIndex = currentPage + 2;
}
}
else
{
endIndex = (pagerSpan - currentPage) + 1;
}
if (endIndex - (pagerSpan - 1) > startIndex)
{
startIndex = endIndex - (pagerSpan - 1);
}
if (endIndex > pageCount)
{
endIndex = pageCount;
startIndex = ((endIndex - pagerSpan) + 1) > 0 ? (endIndex - pagerSpan) + 1 : 1;
}
//Add the First Page Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "First", Value = "1" });
}
//Add the Previous Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "<<", Value = (currentPage - 1).ToString() });
}
for (int i = startIndex; i <= endIndex; i++)
{
pages.Add(new Page { Text = i.ToString(), Value = i.ToString(), Selected = i == currentPage });
}
//Add the Next Button.
if (currentPage < pageCount)
{
pages.Add(new Page { Text = ">>", Value = (currentPage + 1).ToString() });
}
//Add the Last Button.
if (currentPage != pageCount)
{
pages.Add(new Page { Text = "Last", Value = pageCount.ToString() });
}
//Clear existing Pager Buttons.
pnlPager.Controls.Clear();
//Loop and add Buttons for Pager.
int count = 0;
foreach (Page page in pages)
{
Button btnPage = new Button();
btnPage.Location = new System.Drawing.Point(38 * count, 5);
btnPage.Size = new System.Drawing.Size(35, 20);
btnPage.Name = page.Value;
btnPage.Text = page.Text;
btnPage.Enabled = !page.Selected;
btnPage.Click += new System.EventHandler(this.Page_Click);
pnlPager.Controls.Add(btnPage);
count++;
}
}
private void Page_Click(object sender, EventArgs e)
{
Button btnPager = (sender as Button);
this.BindGrid(int.Parse(btnPager.Name));
}
public class Page
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
Another Approach for this problem:
public class PagedGrid : DataGridView
{
Paging pg;
SQLQuery s;
public void SetPagedDataSource( SQLQuery s, BindingNavigator bnav)
{
this.s = s;
int count = DataProvider.ExecuteCount(s.CountQuery);
pg = new Paging(count, 5);
bnav.BindingSource = pg.BindingSource;
pg.BindingSource.PositionChanged += new EventHandler(bs_PositionChanged);
//first page
string q = s.GetPagingQuery(pg.GetStartRowNum(1), pg.GetEndRowNum(1), true);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
void bs_PositionChanged(object sender, EventArgs e)
{
int pos = ((BindingSource)sender).Position + 1;
string q = s.GetPagingQuery(pg.GetStartRowNum(pos), pg.GetEndRowNum(pos), false);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
public void UpdateData()
{
DataTable dt = (DataTable)DataSource;
using (SqlConnection con = new SqlConnection(DataProvider.conStr))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(s.CompleteQuery, con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.UpdateCommand = cb.GetUpdateCommand();
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.Update(dt);
}
MessageBox.Show("The changes are committed to database!");
}
}
/// <summary>
/// Gives functionality of next page , etc for paging.
/// </summary>
public class Paging
{
public int _totalSize = 0;
private int _pageSize = 0;
public int TotalSize
{
get
{
return _totalSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_totalSize = value;
}
}
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_pageSize = value;
}
}
public Paging(int totalSize, int pageSize)
{
this.TotalSize = totalSize;
this.PageSize = pageSize;
}
public int GetStartRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return 1 + ((PageNum - 1) * _pageSize);
}
public int GetEndRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return _pageSize + ((PageNum - 1) * _pageSize);
}
public int GetPageCount()
{
return (int)Math.Ceiling(TotalSize / (decimal)PageSize);
}
public bool IsFirstPage(int PageNum)
{
if (PageNum == 1)
{
return true;
}
return false;
}
public bool IsLastPage(int PageNum)
{
if (PageNum == GetPageCount())
{
return true;
}
return false;
}
private int _currentPage = 1;
public int CurrentPage
{
get
{
return _currentPage;
}
set
{
_currentPage = value;
}
}
public int NextPage
{
get
{
if (CurrentPage + 1 <= GetPageCount())
{
_currentPage = _currentPage + 1;
}
return _currentPage;
}
}
public int PreviousPage
{
get
{
if (_currentPage - 1 >= 1)
{
_currentPage = _currentPage - 1;
}
return _currentPage;
}
}
private BindingSource _bindingSource = null;
public BindingSource BindingSource
{
get
{
if (_bindingSource == null)
{
_bindingSource = new BindingSource();
List<int> test = new List<int>();
for (int i = 0; i < GetPageCount(); i++)
{
test.Add(i);
}
_bindingSource.DataSource = test;
}
return _bindingSource;
}
}
}
/// <summary>
/// Query Helper of Paging
/// </summary>
public class SQLQuery
{
private string IDColumn = "";
private string WherePart = " 1=1 ";
private string FromPart = "";
private string SelectPart = "";
public SQLQuery(string SelectPart, string FromPart, string WherePart, string IDColumn)
{
this.IDColumn = IDColumn;
this.WherePart = WherePart;
this.FromPart = FromPart;
this.SelectPart = SelectPart;
}
public string CompleteQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select {0} from {1} where {2} ", SelectPart, FromPart, WherePart);
}
else
{
return string.Format("Select {0} from {1} ", SelectPart, FromPart);
}
}
}
public string CountQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select count(*) from {0} where {1} ", FromPart, WherePart);
}
else
{
return string.Format("Select count(*) from {0} ", FromPart);
}
}
}
public string GetPagingQuery(int fromrow, int torow, bool isSerial)
{
fromrow--;
if (isSerial)
{
return string.Format("{0} where {1} >= {2} and {1} <= {3}", CompleteQuery, IDColumn, fromrow, torow);
}
else
{
string select1 = "";
string select2 = "";
if (WherePart.Trim().Length > 0)
{
select1 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, torow.ToString());
select2 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, fromrow.ToString());
}
else
{
select1 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, torow.ToString());
select2 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, fromrow.ToString());
}
if (fromrow <= 1)
{
return select1;
}
else
{
return string.Format("{0} except {1} ", select1, select2);
}
}
}
}
using it:
private void Form1_Load(object sender, EventArgs e)
{
SQLQuery s = new SQLQuery("*", "table", "", "id");
pagedGrid1.SetPagedDataSource(s, bindingNavigator1);
}
Note: The DataPrivier class is not included here , it is a simple class that returns datatable from any source.
Try this,
this code is for OleDb, but also works for SqlServer connections.
The dt (DataTable) object is filled with selected page rows, assuming that page starts with 1 (not 0)
public DataTable getData(string sql, int pgNo, int totalRows)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
DataSet ds;
conn.Open();
ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
adapter.Fill(ds, (pgNo-1)*totalRows, totalRows, "Table");
conn.Close();
dt = ds.Tables[0];
}
catch (Exception ex)
{if (conn != null) conn.Dispose();}
return dt;
}
My answer is 10years late and I can't begin to explain why. But I think what is important is that I have something to offer. :D
I love to solve problems in the simplest way possible and by far this is the simplest way I use. If there are any issues with it, am glad to fix it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter pagingAdapter;
DataSet pagingDS;
int scrollVal; // This defines how many more data sets there are to load
int rowsPerPage = 10; // This defines the total number of rows to show
public Form1()
{
InitializeComponent();
scrollVal = 0;
}
private void BtnShowresults_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
pagingAdapter = new SqlDataAdapter(sql, connection);
pagingDS = new DataSet();
connection.Open();
//This part will get the total number of records from the query
pagingAdapter.Fill(dataSetProjects);
DataTable dataTable = pagingDS.Tables[0];
int rowCount = Convert.ToInt32(dataTable.Rows.Count);
this.btnShowresults.Tag = rowCount; // We set it to the button tag
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "Authors_table");
connection.Close();
dataGridView1.DataSource = pagingDS;
dataGridView1.DataMember = "Authors_table";
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (scrollVal < = 0)
{
scrollVal = 0;
} else
{
scrollVal -= rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
private void BtnNext_Click(object sender, EventArgs e)
{
Button btnShowresults = (Button)pnSearch.Controls["btnShowresults"];
int resCount = Convert.ToInt32(btnShowresults.Tag);
if (scrollVal <= resCount)
{
scrollVal = rowsPerPage;
} else
{
scrollVal = rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
}
}
This code is found on http://csharp.net-informations.com/datagridview/csharp-datagridview-paging.htm. It had a few bugs I needed to fix. Consider this a cleaned up version.
Paging emulation with RadGridView for WinForms is possible, especially if we take full advantage of LINQ. This approach also gives us another advantage - client performance. The data processing (filtering, sorting and paging) is obviously done by the SQL server, which is fully optimized for such things, rather than the application. The client only processes and shows one page at a time, rather than all million records. Here I do not use RadGridView’s Virtual Mode - this is a topic for a more advanced blog post.
this link my help you :paging-with-radgridview
https://www.telerik.com/blogs/emulating-paging-with-radgridview-for-winforms-and-linq-with-1-million-records
and the code is:
private void BindGrid()
{
this.radGridView1.GridElement.BeginUpdate();
IQueryable queryable = new DataClasses1DataContext().MyTables.AsQueryable();
if (!String.IsNullOrEmpty(where))
{
queryable = queryable.Where(where);
}
if (!String.IsNullOrEmpty(orderBy))
{
queryable = queryable.OrderBy(orderBy);
}
radGridView1.DataSource = queryable.Skip(currentPageIndex * pageSize).Take(pageSize);
this.radGridView1.GridElement.EndUpdate(true);
EnableDisablePager();
}
I did manual paging on my datagridview. I hope this helps
private void btnBack_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = a - 100;
int d = b - 100;
if (lblmin.Text != "1")
{
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between " + c.ToString() + " and " + d.ToString() + "", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblcount.Text = c.ToString();
lblmax.Text = d.ToString();
}
else
{
btnBack.Visible = false;
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = b + 1;
int d = b + 100;
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between "+c.ToString()+" and "+d.ToString()+"", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblmin.Text = c.ToString();
lblmax.Text = d.ToString();
btnBack.Visible = true;
}
and i put this code on form_load():
lblmin.Text = "1";

Categories