So finally.. I have my repeater working as I want it to be full of buttons, radio button, image buttons, update panels, AJAX modal popups and a heavy code behind each event.
found out that my repeater getting very slow when the items exceeds 20, so I used paging as a solution. the problem is when I do changes and move on to the next page, all changes are gone when getting back to the previous page. (checked radios, labels, etc all back to normal state).
please help, my system is in production now.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadTasks();
}
void loadTasks()
{
string evalidxxx = Request.QueryString["eval_id"].Trim().Replace(" ", "");
SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["GappConnectionString2"].ConnectionString);
try
{
conn.Open();
SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT Prog_Task_link.pt_seq, Tasks.task_name, Tasks.task_id FROM Tasks INNER JOIN Prog_Task_link ON Tasks.task_id = Prog_Task_link.task_id INNER JOIN Programs ON Prog_Task_link.prog_id = programs.prog_id INNER JOIN Data_Tracker_prepare ON Programs.prog_id = Data_Tracker_prepare.dtpre_prog_id WHERE Data_Tracker_prepare.eval_id =" + evalidxxx, conn);
System.Data.DataTable dt = new System.Data.DataTable();
sqlAdapter.Fill(dt);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = dt.DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 10;
objPds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
+ objPds.PageCount.ToString();
//Disable Prev or Next buttons if necessary
LinkPrevPage.Enabled = !objPds.IsFirstPage;
LinkNextPage.Enabled = !objPds.IsLastPage;
rptr1.DataSource = objPds;
rptr1.DataBind();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally { conn.Close(); }
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default to showing the first page
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void LinkPrevPage_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
loadTasks();
}
protected void LinkNextPage_Click(object sender, EventArgs e)
{
CurrentPage += 1;
loadTasks();
}
if you are using .net 4.0 you can use EnablePersistedSelection="True"
sorry to say but this can not be done..
When you are in page one, the rest pages are not actual exists in repeater.
after paging to next page next data will be load so previous data will be reset
i mean to say, When you ask to select all radios, buttons,check boxes are mean what you see. After you change page the other controls are set to default (probably unchecked or reset)
So re design your user interface for what you want to do. And as my suggestion take another button to save the current state of the page.. and then go to next page..
anything other that i can help ??
Related
I am using Visual studio 2012 and have made a windows form application, for one of the forms I am using a datagridview which shows the information of a table from the SQL database.
I have made the form load information from the datagridview rows directly into a textbox automatically.
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM Stock", con);
DataTable DATA = new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource = DATA
txtStock3.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Descriptioncombo2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
txtprice2.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
The problem is that I need to add a previous button and a next button so that users can navigate through the datagridview rows and see the information in a textbox from each column of a datagridview row. I have looked at similar questions and have browsed through the internet to look for a solution to my problem but i can't seem to find a way which works with my code. Also could you tell me how to add a line of code which tells the user that there is no more rows to select if they click next through all rows of the database.
One way to provide navigation is by using a BindingNavigator where you can remove unnecessary buttons and for TextBox you can data binding.
Code responsible for loading data. Replace the console.writeline in the catch as you see fit e.g. write to a log file etc.
public class DataOperations
{
public DataTable LoadCustomers()
{
DataTable dtCustomers = new DataTable();
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"SELECT [Identfier], [CompanyName],[ContactName],[ContactTitle] FROM [NORTHWND1.MDF].[dbo].[Customers]";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
try
{
cn.Open();
dtCustomers.Load(cmd.ExecuteReader());
dtCustomers.Columns["Identfier"].ColumnMapping = MappingType.Hidden;
dtCustomers.Columns["ContactTitle"].ColumnMapping = MappingType.Hidden;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return dtCustomers;
}
}
On a form, one BindingNavigator, one dataGridView, one TextBox
DataOperations dataOps = new DataOperations();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = dataOps.LoadCustomers();
dataGridView1.DataSource = bsCustomers;
bindingNavigator1.BindingSource = bsCustomers;
txtContactTitle.DataBindings.Add("Text", bsCustomers, "ContactTitle");
An alternate to the BindingNavigator is to make the BindingSource form level, private variable. Then in buttons call BindingSource.Move method e.g. bsCustomers.MoveFirst(). Of course there is MoveNext, MoveLast and MovePrevious too.
//first
int i = 0;
this.dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[dataGridView1.CurrentCell.ColumnIndex];
//prev
int prev = dataGridView1.CurrentRow.Index - 1;
if (prev >= 0)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[prev].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
//next
int next = dataGridView1.CurrentRow.Index + 1;
if (next < dataGridView1.Rows.Count)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[next].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
//last
int i = dataGridView1.Rows.Count - 1;
if (i < dataGridView1.Rows.Count)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
As an alternate to Karen's solution, if you prefer/must go with buttons to navigate then you'll want to handle the CurrentCellChanged event as well as the following button Click events:
private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentRow != null)
{
txtStock3.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Descriptioncombo2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
txtprice2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
this.prevButton.Enabled = this.dataGridView1.CurrentRow.Index > 0;
this.nextButton.Enabled = this.dataGridView1.CurrentRow.Index < this.dataGridView1.Rows.Count - 1;
}
}
private void PrevButton_Click(object sender, EventArgs e)
{
int prev = this.dataGridView1.CurrentRow.Index - 1;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[prev].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}
private void NextButton_Click(object sender, EventArgs e)
{
int next = this.dataGridView1.CurrentRow.Index + 1;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[next].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}
The CurrentCellChanged event will handle logic for if you can click Previous or Next. Their respective click events simply move the current cell backwards or forwards one row.
You configure the comulmns in the grid to be your matching types. Then after the query you bind the data to this gridView. You add two buttons where the "next" button will fetch the currentselectedrow of the grid, and set it's follower to be the selected one. previous will do the opposite. This is a small pain in the ass. I hate grids in WinForms. The last 4 years, since I did not see them, have been the happiest years of my lif
I have a task to complete.. i must populate a list view from database and show in column wise and on a button click show it in a row wise... i just completed populating list view from database. now how do i display it it column wise and row wise... please help me...
This is the code i have tried to populate the database...
public partial class DtposMDIParentSystem : Form
{
List<object[]> result = new List<object[]>();
public DtposMDIParentSystem()
{
InitializeComponent();
//create the database connection
OleDbConnection aConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposDatabase.accdb;");
//create the command object and store the sql query
OleDbCommand aCommand = new OleDbCommand("SELECT * FROM Food", aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader reader = aCommand.ExecuteReader();
int i = 0;
while (reader.Read())
{
result.Add(new Object[reader.FieldCount]);
reader.GetValues(result[i]);
}
reader.Close();
aConnection.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Invalid Masseage = " + ex.Message);
}
}
private void cmdOlives_Click(object sender, EventArgs e)
{
if (result.Count > 0)
{
string temp = "";
for (int i = 0; i < result[1].Length; i++)
{
temp += result[1][i] + " ";
}
TableOrderListView.Items.Add(temp);
}
}
}
You can achieve something like that by switching between different view modes:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listView1.View = View.Details;
listView1.HeaderStyle = ColumnHeaderStyle.None;
listView1.Columns[0].Width = listView1.ClientSize.Width - 25;
listView1.Height = 244;
}
else
{
listView1.View = View.List;
listView1.Columns[0].Width = 50;
listView1.Height = 44;
}
}
You need to add one Column for Details view to work!
Note that you will have to adapt the size of the Listview:
In Details mode it will need to be tall enough to show several items
In List mode it will have to to rather wide but must not be tall enough to show more than one item (plus the scrollbar)!
If instead you mean to switch rows and columns you will have to do that in your datasource!
I have a View button on my webpage. As soon as a user clicks on this button, through a web service data is fetched and then data is bound to grid view. But when the grid view loads it only shows the number of rows mentioned in PageSize property of the grid and does not show page numbers.
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
grdSearchResult.DataSource = dt.DataSet.Tables["Result"];
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
The Result DataSet contains 5000 rows with 30 columns each. When the gridView loads all I can see is just 100 records (as PageSize=100). How can I page the results? The data needs to be fetched at button click only. The code for gridView page index change is as follows:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
Hello Rishik please check below link for gridview paging:
http://www.codeproject.com/Articles/816953/How-To-Implement-Paging-in-GridView-Control-in-ASP
http://www.c-sharpcorner.com/UploadFile/rohatash/gridview-paging-sample-in-Asp-Net/
You can store your data in a Viewstate or Session variable, I recommend to use a property as wrapper like this:
private DataTable dtStored
{
get { return (ViewState["dt"] == null) ? null : (DataTable)ViewState["dt"]; }
set { ViewState["dt"] = value; }
}
now you can bind your DataTable and save it in the property:
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
dtStored = dt.DataSet.Tables["Result"];
grdSearchResult.DataSource = dtStored;
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
and in the IndexPageChanging method just add a line:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.DataSource = dtStored;
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
If your data is too large maybe it could be better to store it in a Session variable than in a Viewstate, because the second one is going to travel from the Client to the Server and from the Server to the Client in every Postback while you stay in the same page or until you set the variable to null
Windows: 7 Home Premium
Visual Studio: 2012
Language: C#
SQL: Server 2008
I am binding some labels and an Image to a DataReader, which is reading from a local DataBase.
The header label, and the Image URL of the image are binding properly, but the rest of the labels only get populated after I refresh the page.
The first image shows the page after I clicked on the user profile link. Notice that the 3 labels in the page have incorrect information:
After a full page refresh, the data is displayed properly:
The code goes as follows
private static string _acceptingChallenges = "0";
private static string _curUser;
private static string _website = "[None]";
private static string _dateJoined = DateTime.Now.ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["user"]))
{
_curUser = (Request.QueryString["user"]);
pnlProfilePublic.Visible = true;
pnlProfilePrivate.Visible = false;
PopulatePublic();
}
else
{
if (!string.IsNullOrEmpty((string) Session["Nickname"]))
{
_curUser = Session["Nickname"].ToString();
pnlProfilePublic.Visible = false;
pnlProfilePrivate.Visible = true;
PopulatePrivate();
}
else
{
Response.Redirect("~/Default.aspx");
}
}
InitiateData();
}
private void InitiateData()
{
if (Master == null) return;
Label lblTitle = (Label)Master.FindControl("lblTitle");
const string strSql = "SELECT * FROM vwGetProfileDetails WHERE memberNickname=#member";
var sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text };
sqlComm.Parameters.Add(new SqlParameter("#member", SqlDbType.VarChar, 20)).Value = _curUser;
var rdr = sqlComm.ExecuteReader();
int count = 0;
while (rdr.Read())
{
imgProfile.ImageUrl = rdr["memberAvatarLocation"].ToString();
lblTitle.Text = _curUser + "'s Profile Page";
_acceptingChallenges = rdr["memberAcceptingChallenge"].ToString();
_website = rdr["memberWebsite"].ToString();
_dateJoined = rdr["dateAdded"].ToString();
count = count + 1;
}
rdr.Close();
DataConn.Disconnect();
Response.Write(count);
}
PopulatePublic and PopulatePrivate are called before InitiateData... So they will be stored in the static strings and only populated next time the page is called.
If you are using ASP.Net controls then auto view state will probably be enabled so on postback the controls will be repopulated. So you can do lblWebsite.Text = rdr["memberWebsite"].ToString(); and let ASP.NET manage viewstate.. no need for static strings..
Does _curUser have a value the first time InitiateData is called? I don't think so
Also, you don't want to be using static variables on a web page.
I have a very strange issue where SelectionList always returns NULL when i try check its Selected Item/Value. I Googled a bit and I found out that when i click the submit button, the page is being refreshed and the SelectionList is being data bound again so it will revert back to its original behavior.
Then i tried enclosing the binding code in the Page_Load event in a !IsPostBack but still when i try to access the Selected property it is null and an exception is thrown.
Any help would be greatly appreciated.
My code goes something like this... (the braces are not matched properly)
static SelectionList[] Symptoms;
static string UserID = "";
cmbSymptoms1,cmbSymptoms2,cmbSymptoms3 and cmbSymptoms4 are SelectionLists. I took them in to an array of SelectionList and then set the properties.
I had to make them static or else when i click the button to update, they will not retain their values. Any idea why they don't retain the values?
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
//System.Diagnostics.Debug.WriteLine("Not IsPostBack");
if (Request.QueryString["id"] != null && Request.QueryString.ToString() != "")
{
//System.Diagnostics.Debug.WriteLine("id query string is not null :- " + Request.QueryString["id"]);
myclass = new Class1();
UserID = Request.QueryString["id"];
Symptoms = new SelectionList[4];
Symptoms[0] = cmbSymptoms1;
Symptoms[1] = cmbSymptoms2;
Symptoms[2] = cmbSymptoms3;
Symptoms[3] = cmbSymptoms4;
System.Data.DataTable dt = myclass.getAllSymptoms();
foreach (SelectionList listItem in Symptoms)
{
listItem.DataSource = dt;
listItem.DataTextField = "symptomsname";
listItem.DataValueField = "symptomsid";
listItem.DataBind();
listItem.Items.Insert(0, new MobileListItem("None"));
}
And in the update button click event
protected void cmbUpdate_Click(object sender, EventArgs e)
{
foreach (SelectionList listItem in Symptoms)
{
if (listItem.SelectedIndex != 0)
{
cmd.CommandText = "INSERT INTO Patient_Symptom (patientid,symptomid) VALUES (" + UserID + ",'" + listItem.Selection.Value + "')";
cmd.ExecuteNonQuery();
}
}
}
You can try two things. Try placing the databinding code in the PreRender event. The second and better option would be to use an ObjectDataSource controls and bind the control declaratively.