Showing a dynamic grid view from SQL select statement - c#

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

Related

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:

Best way to load data from DB and show in GridView

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

transfer value from gridview to textbox , is it possible?

i have a credit request registration page. well its just a normal registration page that includes name, address, company, and credit request (money). after which, it is viewed from a gridview in the admin page(viewcredirequest.aspx) here is the code of the aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="table table-hover table-striped">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress"
SortExpression="EmailAddress" />
<asp:BoundField DataField="CompanyAddress" HeaderText="CompanyAddress"
SortExpression="CompanyAddress" />
<asp:BoundField DataField="IncomeRange" HeaderText="IncomeRange"
SortExpression="IncomeRange" />
<asp:BoundField DataField="CreditRequest" HeaderText="CreditRequest"
SortExpression="CreditRequest" />
<asp:BoundField DataField="ContactNumber" HeaderText="ContactNumber" SortExpression="ContactNumber" />
</Columns>
</asp:GridView>
and here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IslandGasAdminFM"] != null)
{
bindgrid();
Label1.Text = "- Finance Manager";
}
else
{
Response.Redirect("LogIn.aspx");
}
}
public void bindgrid()
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select * from CreditRequests ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select * from CreditRequests", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
My DB values are as follows: LastName, FirstName CompanyName, EmailAddress, CompanyAddress, IncomeRange, Creditrequest and ContactNumber. The Creditrequest is taken from a dropdown list.
well what i want is to transfer the credit request value from the gridview to a textbox in my viewprofile.aspx. and another thing, what i have in mind is that when i click a link on a specific row, the credit request value will then be available on the viewprofile of that of the username? please help me to get some references or any idea on how to do this. thank you!
its like when you approve the credit request, the credit request value will be passed on by the profile page of that username through a textbox.

where am i going wrong ? Controlling gridview column value

<asp:HyperLinkField DataNavigateUrlFields="runId" DataTextField="Percent" ControlStyle-CssClass="hlink" HeaderText="% SEEN" ItemStyle-Width="6%" DataNavigateUrlFormatString="run.aspx?runId={0}" ItemStyle-Font-Underline="true"/>
The above is a column from my grid view.Lets call this column 'x'.
I am trying to control the value of x in .cs file as below:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[8].Text.Equals("0"))
{
e.Row.Cells[13].Text = "0%";
return;
}
int p,q;
GridViewRow item = e.Row;
SqlConnection con = new SqlConnection(connectionstring.ToString());
string selectSQL = " SELECT COUNT(*) AS 'Count' FROM Analysed WHERE runId =#myvar group by runId";
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#myvar", item.Cells[0].Text);
SqlDataReader reader;
try
{
con.Open();
Int32.TryParse(item.Cells[8].Text, out p);
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
Int32.TryParse( reader["Count"].ToString(),out q);
item.Cells[13].Text =(q/p).ToString() + "%";
}
reader.Close();
}
}
I get an exception saying "An exception of type 'System.ArgumentOutOfRangeException' occurred in System.Web.dll but was not handled in user code Additional information: Specified argument was out of the range of valid values".This occurs in the lines :
if (e.Row.Cells[8].Text.Equals("0"))
{
e.Row.Cells[13].Text = "0%";
return;
}
Can anyone help ?
EDIT :
GridView Code :
<asp:GridView ID = "GridView2" runat = "server" HorizontalAlign="Center"
DataSourceID = "source" AutoGenerateColumns = "False" AllowPaging="True" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="runId" DataTextField="runId" HeaderText = "RUN ID" ControlStyle-CssClass="hlink" DataNavigateUrlFormatString="runanalysis.aspx?runId={0}" ItemStyle-Width="5%" ItemStyle-Font-Underline="true" />
<asp:HyperLinkField DataField="link" HeaderStyle-ForeColor="White" HeaderStyle-Font-Underline="true" ItemStyle-Width="10%" ItemStyle-Font-Underline="true"/>
<asp:BoundField DataField="Family" HeaderText="Product Family" ItemStyle-Width="7%" />
<asp:BoundField DataField = "Date" DataFormatString="{0:MM/dd/yy}" ItemStyle-Width="7%"/>
<asp:BoundField DataField = "Number" ItemStyle-Width="5%"/>
<asp:BoundField DataField = "Total" ItemStyle-Width="7%" />
<asp:BoundField DataField="Pass" ItemStyle-Width="7%" HeaderText="Pass Percent" DataFormatString="{0}%" />
<asp:BoundField DataField="pass" ItemStyle-Width="7%"/>
<asp:BoundField DataField="fail" ItemStyle-Width="7%"/>
<asp:BoundField DataField="Owner" ItemStyle-Width="7%"/>
<asp:BoundField DataField="Lang" ItemStyle-Width="5%"/>
<asp:BoundField DataField="Plat" ItemStyle-Width="7%"/>
<asp:BoundField DataField="Flavor" ItemStyle-Width="7%"/>
<asp:HyperLinkField DataNavigateUrlFields="runId" DataTextField="Percent" ControlStyle-CssClass="hlink" HeaderText="% SEEN" ItemStyle-Width="6%" DataNavigateUrlFormatString="run.aspx?runId={0}" ItemStyle-Font-Underline="true"/>
<asp:BoundField DataField="AutomationType" HeaderText ="Automation Type" ItemStyle-Width="7%"/>
</Columns>
</asp:GridView>
The number of cells in GridView2 are probably less than the cell you are trying to access. I think the number of cells (columns) are 13 and you have to use index,12 instead of 13. Its better to check the number of cells before accessing one of those.
if (e.Row.Cells.Count > 12 && e.Row.Cells[8].Text.Equals("0"))
{
e.Row.Cells[12].Text = "0%";
return;
}
Edit based on OP comments
You are trying to access the value that is not yet being assigned in RowDataBound event. In this event you can access the data item and parse it instead of parsing the control/cells.
Change
Int32.TryParse(item.Cells[8].Text, out p);
To
p = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ColumnFromDatabase"));
Note: Same goes for other columns values.

Search query returns none

I have a stored procedure in SQL that searches employee details. When it finds something,it returns and displays the data in a gridview. But how can I handle if it did not return anything? like when 'no record is found'?
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("[Reader].[usp_SearchUser]", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#empID", SqlDbType.Int).Value = this.EmpID;
con.Open();
int result = com.ExecuteNonQuery();
if (result == 0)
{
this.NoRecord = "No Record Found";
}
else
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
search.DataSource = ds;
search.DataBind();
}
}
}
Did not get what is your exact question? do you want the gridview property when there is no data then it will show as no records found i.e. EmptyDataText="No records Found"
e.g.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No records Found">
<Columns>
<asp:boundfield datafield="empID" headertext="Employee ID"/>
<asp:boundfield datafield="empName" headertext="Employee Name"/>
</Columns>
</asp:GridView>
I suppose you use a webcontrol GridView? So you might use the GridView.EmptyDataTemplate to have full control of what to render if no data has been bound.
<asp:gridview id="yourGridView" runat="server">
<emptydatatemplate>
No Data Found!
<img src="noData.jpg"/>
</emptydatatemplate>
</asp:gridview>
Or just use EmptyDataText Property if you just want to show a text Message
<asp:gridview id="yourGridView" emptydatatext="No Data Found" runat="server">
....
</asp:gridview>

Categories