Best way to load data from DB and show in GridView - c#

I am newbie to the ASP.Net world and have a confusion on how to approach the below scenario.
In my application I have to fetch the data from the database when page is loaded and show this in a GridView. The table currently has around 1000 records with about 7 columns. But the data will keep growing.
Here is the code of how I am binding the data to the grid.
protected void Page_Load(object sender, EventArgs e)
{
var data = new AppsAuthData().GetAllUsers();
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
}
I came to know that on every post back above code is getting executed (which obviously is not good). So I added the following to that start of the function
if (IsPostBack)
return;
var data = new AppsAuthData().GetAllUsers();
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
Page Markup
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="RemoveUsers.aspx.cs" Inherits="AppsAuth.Authencations.RemoveUsers" %>
This again has an issue that after Postbacks, GridView has nothing to show. So next I saved my results to the ViewState and on each post back i was retrieving/updating the ViewState.
But since data can be huge in some scenarios, so what are best options available to deal with such issues?
GridView snippet
<asp:GridView ID="gridUsersInfo" runat="server" Width="100%" ForeColor="#333333" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="false" OnSorting="UserInfo_Sorting" OnRowEditing="gridUsersInfo_RowEditing"
OnPageIndexChanging="gridUsersInfo_PageIndexChanging" AutoGenerateEditButton="True">
> <Columns>
<asp:BoundField DataField="USER_ID" ReadOnly="True" HeaderText="ID" SortExpression="USER_ID" />
<asp:BoundField DataField="USER_NAME" ReadOnly="False" HeaderText="User Name" SortExpression="USER_NAME" />
</Columns>
</asp:GridView>
protected void gridUsersInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridUsersInfo.PageIndex = e.NewPageIndex;
gridUsersInfo.DataBind();
}

Instead of putting everything on PageLoad. You can put a button and write the code to populate GridView in the click event of that button.
Using the asp.net control Gridview with pagination enabled will do this for you.
Check the following example:
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="Customer ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Implementing Pagination
The event handler is called when the page is changed inside the GridView.
The value of the PageIndex of the Page which was clicked is present inside the NewPageIndex property of the GridViewPageEventArgs object and it is set to the PageIndex property of the GridView and the GridView is again populated by calling the BindGrid function.
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Source : http://www.aspsnippets.com/Articles/Paging-in-ASPNet-GridView-Example.aspx

What you have to do is just bind bind gridview when !IsPostback in page_load
if(!IsPostBack)
{ var data = new AppsAuthData().GetAllUsers();
ViewState["UserData"] = data;
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
}
Hear is an example : Asp.Net Bind Grid View

In .aspx file
<form runat="server" onload="Page_Load">
<asp:GridView runat="server" ID="gridEvent" AutoGenerateColumns="False" BackColor="White"
BorderStyle="None" BorderWidth="0px" class="table mb-0"
>
<RowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="EventId" HeaderText="#" />
<asp:BoundField DataField="Title" HeaderText="Event Title" />
<asp:BoundField DataField="EventDate" HeaderText="Event Date" />
<asp:BoundField DataField="Location" HeaderText="Venue" />
<asp:BoundField DataField="RegisteredUsers" HeaderText="Registred User(s)" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#FBFBFB" Font-Bold="True" ForeColor="#5A6169" />
</asp:GridView>
</form>
in the .aspx.designer.cs
public partial class Default
{
/// <summary>
/// txtLocation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gridEvent;
}
in the .aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Enable the GridView paging option and
// specify the page size.
gridEvent.AllowPaging = true;
gridEvent.PageSize = 15;
// Initialize the sorting expression.
ViewState["SortExpression"] = "EventId ASC";
// Enable the GridView sorting option.
gridEvent.AllowSorting = true;
BindGrid();
}
}
private void BindGrid()
{
// Get the connection string from Web.config.
// When we use Using statement,
// we don't need to explicitly dispose the object in the code,
// the using statement takes care of it.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConn"].ToString()))
{
// Create a DataSet object.
DataSet dsPerson = new DataSet();
// Create a SELECT query.
string strSelectCmd = "SELECT * FROM EventsList";
// Create a SqlDataAdapter object
// SqlDataAdapter represents a set of data commands and a
// database connection that are used to fill the DataSet and
// update a SQL Server database.
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
// Open the connection
conn.Open();
// Fill the DataTable named "Person" in DataSet with the rows
// returned by the query.new n
da.Fill(dsPerson, "EventsList");
// Get the DataView from Person DataTable.
DataView dvPerson = dsPerson.Tables["EventsList"].DefaultView;
// Set the sort column and sort order.
dvPerson.Sort = ViewState["SortExpression"].ToString();
// Bind the GridView control.
gridEvent.DataSource = dvPerson;
gridEvent.DataBind();
}
}
//Implementing Pagination
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
gridEvent.PageIndex = e.NewPageIndex;
gridEvent.DataBind();
}

Related

How do you do this loading progress in asp.net web forms .net 4.8

The following is from a blazor web app that shows loading text while records are being retrieved. How would you do this in ASP.NET WebForms .Net 4.8?
#page "/fetchemployees"
#inject SampleDataAccess data
<PageTitle>Employee Directory</PageTitle>
<h1>Employee Directory</h1>
#if (employees is not null)
{
foreach (var e in employees)
{
<h3>#e.FirstName #e.LastName</h3>
}
}
else
{
<h3>Loading...</h3>
}
#code {
List<EmployeeModel> employees;
//protected override void OnInitialized()
//{
// employees = data.GetEmployees();
//}
protected override async Task OnInitializedAsync()
{
employees = await data.GetEmployeesCache();
}
}
Are you doing this on first page load, or is there some button you press to show "loading" while say the gridview loads?
if this is a button click on the page, then just add both client side code and server side code to the button click.
So, say a button, and this gv:
<asp:Button ID="cmdLoad" runat="server" Text="Load Data" CssClass="btn"
OnClick="cmdLoad_Click"
OnClientClick="$('#mywait').show();"/>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" Width="50%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
<div id ="mywait" style="display:none">
<h3>Loading grid - please wait</h3>
<img src="Images/wait2.gif" />
</div>
So, when we click the button, we show the please wait - and a spinner.
Code behind is this:
protected void cmdLoad_Click(object sender, EventArgs e)
{
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4DB))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName",conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
// fake 2 second loading time
System.Threading.Thread.Sleep(2000);
}
}
}
And results look like this:
So, by adding both a client side code and server side to the same button, you get the above effect.

How to Sort data in dataset using dropdownlist?

I am using asp.net webforms application and listing products on page load. I want to sort data when i am selecting a value from dropdownlist. If i use static DataSet i can sort data using dropdownlist but it's not useful when you have visitors more then one.
I don't want to use Session variable for sorting products. What's the alternative to sorting data using dropdownlist? I am listing products on the page, just want to sort. When i click on the dropdown list for sorting, DataSet returns "null" But i can see products on the page in repeater. It doesn't disappear.
Dropdown listing code:
protected DataSet data {get;set;}
protected void dropdown_sort_SelectedIndexChanged(object sender, EventArgs e)
{
if(data != null)
{
ds.Tables[0].DefaultView.Sort = "product_id asc"
}
}
Any suggestion?
Well, we assume then a drop down list to select the column to sort, and then say a gridview.
So, say this markup:
Sort Data by:
<asp:DropDownList ID="DropDownList1" runat="server" Width="120px"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
</asp:DropDownList>
<br />
<asp:GridView ID="GridView1" runat="server" CssClass="table"
AutoGenerateColumns="False" DataKeyNames="ID"
ShowHeaderWhenEmpty="true" Width="40%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
Ok, code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCombo();
LoadGrid();
}
}
void LoadCombo()
{
string OrderList = "Select Order,HotelName,City,FirstName,LastName";
foreach (string sOrder in OrderList.Split(','))
{
DropDownList1.Items.Add(sOrder);
}
}
void LoadGrid(string OrderBy = "")
{
string strSQL = "SELECT * FROM tblHotelsA";
if ( (OrderBy != "") & (OrderBy != "Select Order") )
strSQL += " ORDER BY " + OrderBy;
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And we now have this:
Now, code for the drop down list (note the autopostback=true).
We have this code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadGrid(DropDownList1.Text);
}
So, say we select this from the drop down:
We now see this:

Why is my data set being shortened when I page in my asp gridview?

Its a standard gridview:
<asp:GridView runat="server" ID="gvAlerts" AutoGenerateColumns="false"
DataKeyNames="Id" CssClass="table table-striped table-bordered table-hover"
OnRowDataBound="gvAlerts_RowDataBound"
OnSelectedIndexChanging="gvAlerts_SelectedIndexChanging"
OnRowDeleting="gvAlerts_RowDeleting"
EmptyDataText="There are no alerts to manage."
PageSize="10" AllowPaging="true"
PagerSettings-Position="TopAndBottom"
PagerSettings-Visible="true"
PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="gvAlerts_PageIndexChanging">
<Columns>
<asp:BoundField HeaderText="" DataField="ContractEntity"
SortExpression="Supplier" />
<asp:BoundField HeaderText="Reference" DataField="Reference"
SortExpression="Reference" />
<asp:BoundField HeaderText="Date" DataField="Date"
SortExpression="Date" DataFormatString="{0:dd/MM/yyyy}" />
<asp:BoundField HeaderText="Contact Person" DataField="Username"
SortExpression="Username" />
<asp:BoundField HeaderText="End Date" DataField="EndDate"
SortExpression="EndDate" DataFormatString="{0:dd/MM/yyyy}" />
<asp:BoundField HeaderText="Value" DataField="Value"
SortExpression="Value" DataFormatString="R{0:# ### ###.00}" />
<asp:BoundField HeaderText="Category" DataField="ContractCategory"
SortExpression="Category" />
<asp:CommandField ShowSelectButton="true" SelectText="<i class='glyphicon glyphicon-pencil'></i>" />
<asp:CommandField ShowDeleteButton="true" DeleteText="<i class='glyphicon glyphicon-trash'></i>" />
</Columns>
</asp:GridView>
I can't seem to get the paging working right though.
In the code below I've limited the data to 80 records (for testing purposes). It appears that the data does actually page over when I go to a different page, but that's not all it does; there is also always less data returned every time until eventually paging is no longer possible because there aren't enough records to bind to the gridview.
private List<Alert> _alerts { get; set; }
protected void gvAlerts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvAlerts.PageIndex = e.NewPageIndex;
try
{
PageData(e.NewPageIndex);
}
catch (ArgumentNullException ane)
{
// Get all Alerts data again since the collection was apparently
// emptied on postback.
_alerts = GetAlerts();
PageData(e.NewPageIndex);
}
}
private void PageData(int pageIndex)
{
List<Alert> alerts = _alerts;
if (pageIndex >= 2)
{
alerts = _alerts.Skip(pageIndex * gvAlerts.PageSize).Take(gvAlerts.PageSize).ToList();
}
gvAlerts.DataSource = BuildGridViewModel(alerts);
gvAlerts.DataBind();
}
private List<AlertListViewModel> BuildGridViewModel(List<Alert> alerts)
{
var model = new List<AlertListViewModel>();
var u = HttpContext.Current.User.Identity;
using (var db = new ApplicationDbContext())
{
foreach (Alert alert in alerts)
{
// Due to poor database design, these queries are unavoidable.
var contract = db.Contracts.FirstOrDefault(x => x.Id == alert.ContractId);
var category = db.Categories.FirstOrDefault(x => x.Id == contract.CategoryId).Name;
var entity = db.ContractEntities.FirstOrDefault(x => x.Id == contract.ContractEntityId).Name;
model.Add(new AlertListViewModel
{
// Map model properties.
});
}
}
return model;
}
I understand that the .Skip() and .Take() are probably what's shortening the data set but without those, how am I to change the data that is currently visible on the gridview?
I'm missing something here. What is it? How do I get this gridview paging without losing any data?
The downside of the GridVIew is that all the records are retrieved every time and/or all stored in ViewState. So if you want to use Linq create your own paging method. Below a quick example of how this can be done.
If you still want to use the build-in paging, follow the comment of InitLipton
List<Book> books;
int pageSize = 10;
protected void Page_Load(object sender, EventArgs e)
{
//fill the collection
books = fillBooks();
//create the dynamic pager buttons, this needs to be done on every page load
createPager();
//bind the grid for the first time without postback
if (!IsPostBack)
{
bindGrid(0);
}
}
private void bindGrid(int offSet)
{
//bind the right amount of items to the grid
GridView1.DataSource = books.Skip(offSet).Take(pageSize).ToList();
GridView1.DataBind();
}
private void createPager()
{
//loop for every x items in the collection
for (int i = 0; i < (books.Count / pageSize); i++)
{
//create a linkbutton
LinkButton lb = new LinkButton();
//add the properties
lb.Text = (i + 1).ToString();
lb.CommandArgument = i.ToString();
//bind the command method
lb.Command += Lb_Command;
//add the linkbutton to the page
PlaceHolder1.Controls.Add(lb);
//add some spacing
PlaceHolder1.Controls.Add(new Literal() { Text = " " });
}
}
private void Lb_Command(object sender, CommandEventArgs e)
{
//rebind the grid with the next 10 items
bindGrid(Convert.ToInt32(e.CommandArgument) * 10);
}
And the aspx
<asp:GridView ID="GridView1" runat="server" EnableViewState="false"></asp:GridView>
<br />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

OnCheckChanged Event of asp:CheckBox Not Firing When Unchecked From Within Nested GridView

I have conducted a lot of searches which included checkchanged or OncheckChanged keyword:
ASP.NET CheckBox does not fire CheckedChanged event when unchecking
https://forums.asp.net/t/1311576.aspx?Checkbox+not+firing+when+unchecking+using+OnCheckedChanged
OnCheckedChanged event not firing
OnCheckedChanged event handler of asp:checkbox does not fire when checkbox is unchecked
But this just doesn't seem to be working although I applied all suggestion from the links given above
I am tring to fire a CheckChanged Event From nested gridview, whose DataSource gets binded in parent grid's OnRowDataBound event.
My aspx markup
<asp:GridView ID="gvDocSchedule" runat="server" AutoGenerateColumns="false" CssClass="table table-striped color-black"
OnRowDataBound="gvDocSchedule_RowDataBound" DataKeyNames="UserID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor:pointer" src="UserPanel/images/Plus12.png" />
<asp:Panel ID="PanelSchedule" runat="server" Style="display:none">
<asp:GridView ID="gvScheduleDayNTime" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField ="ScheduleDay" HeaderText="CheckInTime1"/>
<asp:BoundField ItemStyle-Width="150px" DataField ="CheckInTime1" HeaderText="CheckInTime1"/>
<asp:BoundField ItemStyle-Width="150px" DataField ="CheckOutTime1" HeaderText="CheckOutTime1"/>
<asp:BoundField ItemStyle-Width="150px" DataField ="CheckInTime2" HeaderText="CheckInTime2"/>
<asp:BoundField ItemStyle-Width="150px" DataField ="CheckOutTime2" HeaderText="CheckOutTime2"/>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdnForChkBox" runat="server" value="No" />
<asp:CheckBox ID="CBoxAvailabilityTime1" ViewStateMode="Enabled" Checked="false" Enabled="true" EnableViewState="true" runat="server" Text="See Free TimeSlots For Booking In Time1" AutoPostBack="true" OnCheckedChanged="CBoxAvailabilityTime1_CheckedChanged" />
<br />
<asp:CheckBox ID="CBoxAvailabilityTime2" runat="server" Text="See Free TimeSlots For Booking In Time1" AutoPostBack="true" OnCheckedChanged="CBoxAvailabilityTime2_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ControlStyle-Font-Bold="true" DataField="UserFirstName" HeaderText="Doctor's First Name" />
<asp:BoundField DataField="UserLastName" HeaderText="Doctor's Last Name" />
<asp:BoundField DataField="SpecializationName" HeaderText="Doctor's Specialization" />
<asp:BoundField DataField="HospitalName" HeaderText="Hospital" />
</Columns>
</asp:GridView>
I was trying it with CBoxAvailabilityTime1CheckBox. As you guys can see ViewStateMode and EnableViewState has been taken care of not only in server tag but also in content page's tag, also these properties are true for master page
Parent Grid gets binded when user press a button and nested grid gets binded in parent's OnRowDataBound event
Here is My aspx.cs code
protected void CBoxAvailabilityTime1_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gvParentRow in gvDocSchedule.Rows)
{
if (gvParentRow.RowType == DataControlRowType.DataRow)
{
GridView gvDocSchedulesGetChildGrid = (GridView)gvParentRow.FindControl("gvScheduleDayNTime");
if (gvDocSchedulesGetChildGrid != null)
{
foreach (GridViewRow gvChildRow in gvDocSchedulesGetChildGrid.Rows)
{
CheckBox CBoxAvailabilityTime1 = (CheckBox)gvChildRow.FindControl("CBoxAvailabilityTime1");
CheckBox CBoxAvailabilityTime2 = (CheckBox)gvChildRow.FindControl("CBoxAvailabilityTime2");
if (((CheckBox)CBoxAvailabilityTime1).Checked)
{
CBoxAvailabilityTime2.Enabled = false;
}
if (!((CheckBox)CBoxAvailabilityTime1).Checked)
{
CBoxAvailabilityTime2.Enabled = true;
}
}
}
}
}
}
With this setup CheckChanged Event Fires on Checking.
On Checking it hits Page_ Load skips if(!IsPostBack) (as AutoPostBack=true) and then control is directly transferred to
CBoxAvailabilityTime1_CheckedChanged(object sender, EventArgs e) event handler function
but on the other hand it doesn't fire on unchecking it postsbacks goes to Page load again Skips if(!IsPostBack) and does nothing instead of calling
CBoxAvailabilityTime1_CheckedChanged(object sender, EventArgs e)
"Note:-" Page_Load is not involved. I can't bind parent grid in page_load,
!IsPostBack because I dont need to bind it at first time when page gets loaded rather its binding happens inside a button click event, if a button is clicked only then parent grid must get binded.
Update 1:- This is how I bind data to parent grid
I am calling this function in a button click event
protected void BindDataToGridViewDocInArea()
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
SqlCommand cmdFillGridDocInArea = new SqlCommand("some query with parameter here", con)
cmdFillGridDocInArea.Parameters.AddWithValue("#AID", ddlAskArea.SelectedValue);
SqlDataAdapter sdaFillGridDocInArea = new SqlDataAdapter(cmdFillGridDocInArea);
DataTable dtFillGridDocInArea = new DataTable();
sdaFillGridDocInArea.Fill(dtFillGridDocInArea);
if (dtFillGridDocInArea.Rows.Count > 0)
{
gvDocSchedule.DataSource = dtFillGridDocInArea;
gvDocSchedule.DataBind();
}
else
{
lblError.Text = string.Empty;
lblError.Text = "No Record Exists Against Requst Specified";
}
con.Dispose();
}
}
Tested a stripped down version of you snippet. It seems to be working. When you check CBoxAvailabilityTime1, it disables CBoxAvailabilityTime2. When you uncheck CBoxAvailabilityTime1 the other one is enabled again.
However this is only when the DataBinding of gvDocSchedule is inside an IsPostBack check. When it's not the checkboxes will always go to their default unchecked state after PostBack.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//this works
gvDocSchedule.DataSource = LoadFromDB();
gvDocSchedule.DataBind();
}
//this does not
gvDocSchedule.DataSource = LoadFromDB();
gvDocSchedule.DataBind();
}
Or in your case something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDataToGridViewDocInArea();
}
}

Showing a dynamic grid view from SQL select statement

On my webform for ASP.Net I display a table from SQL Server. However, what I would like to do is offer the user of the web page the ability to check some boxes and only show those particular columns once I refresh the page.
Here is the aspx html:
<div style="width: 1250px; height: 300px; overflow: auto">
<asp:GridView ID="GridView1" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="Silver" RowStyle-BackColor="#EEEEEE" AlternatingRowStyle-BackColor="White"
AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns ="false" AllowPaging="false" OnPageIndexChanging="OnPageIndexChanging" AllowSorting="True">
<Columns>
<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" dataformatstring="{0:MM-dd-yyyy}" />
<asp:BoundField DataField ="Week_Number" HeaderText="Week Number" ItemStyle-Width="150px" />
<asp:BoundField DataField ="Class" HeaderText="Class" ItemStyle-Width="150px" />
<asp:BoundField DataField ="Animal" HeaderText="Animal" ItemStyle-Width="150px" />
<asp:BoundField DataField ="North_Island" HeaderText="North Island" ItemStyle-Width="150px" DataFormatString="{0:F2}" />
<asp:BoundField DataField ="South_Island" HeaderText="South Island" ItemStyle-Width="150px" DataFormatString="{0:F2}" />
<asp:BoundField DataField ="New_Zealand" HeaderText="New Zealand" ItemStyle-Width="150px" DataFormatString="{0:F2}" />
</Columns>
</asp:GridView>
</div>
Here is the bindgrid method:
private void BindGrid()
{
string strConnString = "server= N-1077; Trusted_Connection=yes; database=Slaughter; connection timeout=30";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CONVERT(date, Week_Ending_Date) AS WeekEndingDate," +
"Week_Number, Class, North_Island = CAST(North_Island as float), South_Island = CAST(South_Island as float)," +
"(CAST(North_Island as float)) + (CAST(South_Island as float)) AS New_Zealand," +
"Animal = (CASE WHEN Class = 'Sheep' OR Class = 'Lamb' THEN 'Ovine' WHEN Class = 'Calf' THEN 'Calf' ELSE 'Bovine' END)" +
"FROM Slaughter ORDER BY WeekEndingDate DESC"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Is there a simple way to select particular columns and only show these? i.e. if they were only interested in week_number, class and south_island it would only display the data for those three columns? I don't mind building the SQL query based on the user inputs but it's how I change the boundfield Datafields to reflect on those columns that were selected in that query.
This is one way of doing it with the Visible property.
protected void RefreshSQLDisplay(object sender, EventArgs e)
{
foreach (BoundField col in GridView1.Columns)
{
if (col.DataField == "WeekEndingDate")
{
col.Visible = false;
break;
}
}
}
The disadvantage is that the columns will be still in memory and the sql query will retrieve the data. So it's better to change the sql query after all for performance reasons.
Update: I edited the code as you asked

Categories