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.
Related
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:
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();
}
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
I created a gridview on my approval.aspx page. I am using VS 2014 and SQL Server 2014.
<asp:GridView ID="gv_pending_requests" runat="server" AutoGenerateColumns="False" Width="95%" CellPadding="1" CellSpacing="2">
<Columns>
<asp:BoundField HeaderText="Requested By" DataField="username" />
<asp:BoundField HeaderText="No. of Days" DataField="total_days" />
<asp:BoundField HeaderText="Type of Leave" DataField="leave_type" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Starting" DataField="start_date"/>
<asp:BoundField HeaderText="Ending" DataField="end_date" />
<asp:TemplateField HeaderText="Sanction">
<ItemTemplate>
<asp:Button ID="btn_apprv" Text="Sanction" runat="server" OnClick="btn_apprv" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deny">
<ItemTemplate>
<asp:Button ID="btn_deny" Text="Deny" runat="server" OnClick="btn_deny"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//Now, the code from .cs file:
lbl_uid.Text = Convert.ToString(Session["Username"]);
string connectionstring = #"Data Source=server;Integrated Security=true Initial Catalog=E_M_S";
SqlDataReader rdr;
DataTable dt = new DataTable();
dt.Columns.Add("Requested By");
dt.Columns.Add("Type of Leave");
dt.Columns.Add("Reason");
dt.Columns.Add("Starting");
dt.Columns.Add("Ending");
dt.Columns.Add("No. of Days");
DataRow dr;
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
cmd.CommandType = CommandType.Text;
using (conn)
{
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
dr = dt.NewRow();
dr["Requested By"] = rdr["username"].ToString();
dr["Type of Leave"] = rdr["leave_type"].ToString();
dr["Reason"] = rdr["reason"].ToString();
dr["Starting"] = rdr["start_date"].ToString();
dr["Ending"] = rdr["end_date"].ToString();
dr["No. of Days"] = rdr["total_days"].ToString();
dt.Rows.Add(dr);
dt.AcceptChanges();
gv_pending_requests.DataSource = dt;
gv_pending_requests.DataBind();
conn.Close();
}
}
//Button for sending the E-Mail
protected void btn_apprv(object sender, EventArgs e)
{
Response.Write("<script type='javascript'>alert('The leave has been sanctioned, and mail has been sent to inform the employee of the same.');</script>");
}
Problem1 : It shows below error pointing at the line :- gv_pending_requests.DataSource = dt;
"a field or property with the name 'username' was not found on the selected data source"
Problem 2: I want that a mail be sent to each user according to the button pressed for that row. How do i define an on click event with that mail code?
Please forgive me for missing details,if any. Please help me with this error.
To your Problem 1:
In your SQL-Select-Statement you don't select for the username:
SqlCommand cmd = new SqlCommand("select leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
Instead this code should be:
SqlCommand cmd = new SqlCommand("select username,leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
Otherwise - as stated by the errormessage - the DataReader you use cannot find the column username in the result from the database.
You can test this if you go to your database and fire the SQL-statement there directly, you will see that you do not get the usernames back.
Also, you defined your DataTable with the column Requested by.
dt.Columns.Add("Requested By");
But if you look to your BoundField now, you will see that the DataField is defined as "username":
<asp:BoundField HeaderText="Requested By" DataField="username" />
Either you change the column-name in your DataTable to "username" or you change the DataField in the BoundField to "Requested By".
To your second Problem:
Please read the How-To-Ask-FAQ:
Include just enough code to allow others to reproduce the problem. For
help with this, read How to create a Minimal, Complete, Valid Example.
You don't provide any research or a minimal example which shows us that you at least tried to find a solution.
So I will only give you hints for your "problem", if you got any question then regarding a not working code, please post a new question.
Get Cell Value in C# Gridview when Button clicked on row
How to send email in ASP.NET C#
Use the first link to get the user where the E-Mail should be sent to, and the second link provides the logic to send a E-Mail. Good luck!
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>