GridView PageIndexing - c#

I have a gridView:-
<asp:GridView ID="gvw_Lab_Details" AllowPaging="true" PageSize="3" OnPageIndexChanging="gvw_Lab_Details_PageIndexChanging" runat="server" EmptyDataText="No Previous Enrollments were Found." SkinID="gridviewSkin2">
</asp:GridView>
On the server side:-
public DataSet LabDS
{
get { return (DataSet)ViewState["LabDetails"]; }
set { ViewState["LabDetails"] = value; }
}
#region Initialize.
string _Requestdate = string.Empty;
string _ID = string.Empty;
#endregion
#region Page Methods
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// extracting the Lab_Requested Date from Query String.
_Requestdate = (Request.QueryString["info"]);
_ID = ((MyStateBag)Session["MyStateBag"]).MemberID;
GetLabResults();
}
}
#endregion
private void GetLabResults()
{
using (SqlConnection cn = new SqlConnection(DBConnect.SqlServerConnection))
{
cn.Open();
#region Pulls Existing Enrollments from SQL
DataTable dt = new DataTable();
using (SqlCommand cm = cn.CreateCommand())
{
// Create SQL Statement
StringBuilder ct = new StringBuilder();
ct.AppendLine("SELECT DISTINCT Key, Date, "
+ "NAME_First + ' ' + NAME_MI + ' ' + NAME_Last, "
RESULT_VALUE, RESULT_UNITS ");
ct.AppendLine("FROM [test].[dbo].[test]");
ct.AppendLine("WHERE Date = #Date and ID = #ID");
cm.Parameters.AddWithValue("#Date", _Requestdate);
cm.Parameters.AddWithValue("#ID", _ID);
cm.CommandType = CommandType.Text;
cm.CommandText = ct.ToString();
// Execute
cm.ExecuteNonQuery();
#region Populate Gridview with extracted Data.
SqlDataAdapter dr = new SqlDataAdapter(cm);
dr.Fill(dt);
this.LabDS = new DataSet();
this.LabDS.Tables.Add(dt);
LoadGridView(1);
#endregion
}
#endregion
private void LoadGridView(int PageIndex)
{
gvw_Lab_Details.DataSource = this.LabDS;
gvw_Lab_Details.DataBind();
}
protected void gvw_Lab_Details_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
LoadGridView(e.NewPageIndex);
}
However my indexing doesn't seem to be working aka results of 3 or less are shown on the first page but once there are more than 4 results I get my default "No previous enrollments were found". Any insights on where I am going wrong?
this a .NET web application.

You're missing one important piece of information. You have to tell the GridView which page you are changing to:
protected void gvw_Lab_Details_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvw_Lab_Details.PageIndex = e.NewPageIndex;
LoadGridView(e.NewPageIndex);
}

Related

Asp.Net finding in Code-behind edited values in GridView with autogenerated columns

I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}

Want to display list data in html table C#

enter image here
I want to add list data in the html Table.
The list data can be various, so table rows were dynamic and if List size increase user can use paging in table to move next...
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Date1.Add(sdr["Date"].ToString());
Time.Add(sdr["Time"].ToString());
Event.Add(sdr["Event"].ToString());
Venue.Add(sdr["Venue"].ToString());
}
}
conn.Close();
}
}
for (int i = 0; i < Date1.Count; i++) {
string Date11 = Date1[i];
string Time1 = Time[i];
string Event1 = Event[i];
string Venue1 = Venue[i];
if(Venue1.Contains(country) || Venue1.Contains(Code[0]))
{
Result.Add( Date11 + " " + Time1 + " " + Event1 + " " + Venue1);
}
}
Can someone kindly give me code/hint which can i use in my Project. I will be very thankful to you.
The example below takes care of the following requirements which you've listed in the question:
Generates an HTML table containing your data
Has paging functionality
Supports dynamic columns
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
}
private DataTable GetEvents()
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand("SELECT TOP 100 Date,Time,Event,Venue FROM Event",connection))
{
connection.Open();
var adapter = new SqlDataAdapter(command);
adapter.Fill(table);
connection.Close();
}
}
int rows = table.Rows.Count;//Place breakpoint to make sure table has rows
return table;
}
protected void gvEvents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEvents.PageIndex = e.NewPageIndex;
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
.ASPX:
<form id="form1" runat="server">
<asp:GridView ID="gvEvents" runat="server" AllowPaging="true" PageSize="2" OnPageIndexChanging="gvEvents_PageIndexChanging">
</asp:GridView>
</form>
Output:

Populate gridview from dropdown control (C#)

I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();

How to populate dependant dropdowns in Asp.Net C#

I want to populate TWO dropdownlist, based on selection of first dropdownlist the second dropdownlist will get populated.
Example :
Like i have two dropdownlist namely 1.ddlCountry and 2.ddlState
Now when country is selected then depending on the selected Country the States related with that Country will get populated in the State dropdownlist. I want to achieve this withour reloading the whole page in Asp.Net with coding language as C#.
How can i achieve the same?
Dropdownlist is fetching data from database by executing query.
You can use AJAX toolkit CascadingDropDown as told by Naresh.
OR
use ajax update panel and keep all Dropdowns in it. So the whole page will not load on changing dropdown value.
You didnt give the code to further solution.
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
FillStateByCountry();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
FillLocationByCountryandState();
}
private void FillStateByCountry()
{
DataSet dstFillState;
int CountryId = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
dstFillState = Tbl_State.FillDDLState(CountryId);
ddlState.DataSource = dstFillState;
ddlState.DataTextField = "State";
ddlState.DataValueField = "Id";
ddlState.DataBind();
}
similarly FillLocationByCountryandState();
Add two dropdownlists to your form and name it as cmbStates, cmbCities
when you select state name from cmbStates(dropwdownlist), cmbCities(dropdownlist) generates cities based on state name(cmbStates)
by fetching data from database
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=pbs-server;database=p2p;user id=shekar;password=sekhar#1346");
SqlCommand cmd = new SqlCommand("select states from Country", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Country");
cmbStates.DataSource = ds.Tables[0];
cmbStates.SelectedValue = 0;
con.Close();
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=xxxx;database=xxxx;user id=xxxxr;password=xxxxxx");
SqlCommand cmd = new SqlCommand("select cities from States where cityname = 'cmbStates.SelectedItem.ToString()'", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "States");
cmbCities.DataSource = ds.Tables[0];
cmbCities.SelectedValue = 0;
con.Close();
}
OR
manually adding items
namespace DropDownlist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbStates.Items.Add("Andhra Pradesh");
cmbStates.Items.Add("Tamilnadu");
cmbStates.Items.Add("Karnataka");
cmbStates.SelectedValue = 0;
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStates.SelectedItem.ToString() == "Andhra Pradesh")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Hyderabad");
cmbCities.Items.Add("Guntur");
cmbCities.Items.Add("Vijayawada");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Tamilnadu")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Chennai");
cmbCities.Items.Add("Coimbatore");
cmbCities.Items.Add("ooty");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Karnataka")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Bangalore");
cmbCities.Items.Add("Mangalore");
cmbCities.SelectedValue = 0;
}
else
{
MessageBox.Show("Please Select any value");
}
}
}
}

how to fill DropDownList from database in asp.net?

how to fill DropDownList from database in asp.net ?
and when i pick value from the DropDownList how to catch this event ?
Conn.Open();
SQL = "SELECT distinct city FROM MEN";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
DropDownList1. ?????? (what do to ?)
thanks in advance
You set the DataSource, DataTextField and DataValueField and call DataBind() in order to populate the dropdownlist.
The datasource can be pretty much any IEnumerable and the text and value will be looked up with reflection.
The event you want to catch is the SelectedIndexChanged event - this will fire when you change the selection.
First take the details in a dataset
then the following code will help you:
DropDownList1.DataSource = ds
DropDownList1.DataTextField = "emailid"
DropDownList1.DataValueField = "userid"
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, New ListItem("select", "-1"))
Simple sample code :
DropDownList.DataSource = yourDataSource;
DropDownList.DataTextField = "displayNameColumnName ";
DropDownList.DataValueField = "TheValueColumnName";
DropDownList.DataBind();
This could be a complete walkthrough for you in this case :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
}
protected void Page_Init(object sender, EventArgs e)
{
SqlDataSource sqlDS = new SqlDataSource();
sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
form1.Controls.Add(sqlDS);
DropDownList ddl = new DropDownList();
ddl.ID = "dddlGender";
ddl.DataSource = sqlDS;
ddl.DataTextField = "Gender";
ddl.DataValueField = "GenderID";
form1.Controls.Add(ddl);
// ... Repeat above code 9 times or put in a for loop if they're all the same...
}
private void BindDropDownLists()
{
foreach (Control ctl in form1.Controls)
{
if (ctl is DropDownList)
{
(ctl as DropDownList).DataBind();
}
}
}
//...Wrote separate class for calling this function
FunctionClass obj = new FunctionClass();
List<Designation> details = new List<Designation>();
bool result1 = obj.DataDrop(out details);
if (result1 == true)
{
dropDownDesignation.DataSource = details;
dropDownDesignation.DataTextField = "designation";
dropDownDesignation.DataValueField = "Designation_ID";
dropDownDesignation.DataBind();
dropDownDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
}
//..This function wrote inside FunctionClass and called from aspx.cs page
public bool DataDrop(out List<Designation> designationDetails)
{
designationDetails = new List<Designation>();
conn = new SqlConnection(connectionName);
conn.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DesignationDetails";
userReader = command.ExecuteReader();
if(userReader.HasRows)
{
while(userReader.Read())
{
designationDetails.Add(new Designation()
{
designationId=userReader.GetInt32(0),
designation=userReader.GetString(1)
});
}
}
return true;
}
//..This should declare outside the class but inside the namespace
public class Designation
{
public int designationId { get; set; }
public string designation { get; set; }
}
Another way to bind dropdownlist is...
<asp:DropDownList ID="ddlCity" runat="server" DataValueField="pkId" DataTextField="cityName" DataSourceID="sqlDB">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDB" ConnectionString='$Name of connecitonstring' runat="server" SelectCommand="Select * from tbl_City"></asp:SqlDataSource>

Categories