While implementing a Calendar into asp.net, I originally had text showing up on certain dates, pulling data from a DB. However, now, after changing nothing (to my knowledge), the text no longer appears, but the date box color does still change. Any help would be great. I am also new to asp.net, so it could be a simple mistake.
asp.net code:
<asp:Calendar ID="Calendar" runat="server" OnDayRender="Calendar1_DayRender" BackColor="White" BorderColor="White" BorderWidth="1px" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="300px" NextPrevFormat="FullMonth" Width="500px" >
<DayHeaderStyle Font-Bold="True" Font-Size="8pt" />
<NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" VerticalAlign="Bottom" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#333399" ForeColor="White" />
<TitleStyle BackColor="White" BorderColor="Black" BorderWidth="4px" Font-Bold="True" Font-Size="12pt" ForeColor="#333399" />
<TodayDayStyle BackColor="#CCCCCC" />
</asp:Calendar>
C# code behind:
public partial class HomePageStudent : System.Web.UI.Page
{
SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["Lab3"].ConnectionString);
String sqlQuery;
Dictionary<string, string> importantDates = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
c.Open();
DateTime day;
sqlQuery = #"SELECT * From Internships";
try
{
SqlCommand cmd = new SqlCommand(sqlQuery, c);
SqlDataReader rd;
rd = cmd.ExecuteReader();
while (rd.Read())
{
day = (DateTime)rd["DateStart"];
if (day == e.Day.Date)
{
e.Cell.Controls.Add(new LiteralControl("<p>" + "Application Due:\n" + rd["InternshipTitle"] + "<p>"));
e.Cell.BackColor = System.Drawing.Color.Purple;
e.Cell.ForeColor = System.Drawing.Color.Goldenrod;
e.Cell.Font.Bold = true;
}
}
}
catch (Exception ex)
{
}
c.Close();
}
}
I tried removing formatting and changing around the code a little bit, to no avail.
Of course I solve it a couple minutes after posting...
After renaming the dayrender method, that seemed to fix everything... somehow.
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:
In below datalist represents set of question's and answer.
How to insert the user selected right answer radio button value into database when the user clicks on Final submit button?
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" onselectedindexchanged="rd_CS_CheckedChanged">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<ItemTemplate>
Q:
<asp:Label ID="QLabel" runat="server" Text='<%# Eval("Q") %>' />
<br />
A:
<asp:RadioButton ID="rd_CS" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("A") %>'></asp:RadioButton>
<br />
B:
<asp:RadioButton ID="rd_CS2" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("B") %>'></asp:RadioButton>
<br />
C:
<asp:RadioButton ID="rd_CS3" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("C") %>'></asp:RadioButton>
<br />
D:
<asp:RadioButton ID="rd_CS4" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("D") %>'></asp:RadioButton>
<p style="color: #FF3300">
<asp:Label ID="Correct_AnswerLabel" runat="server"
Text='<%# Eval("Correct_Answer") %>' Visible="False" /></p>
</ItemTemplate>
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:DataList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Quize.mdb"
SelectCommand="SELECT [Q],[A], [B], [C], [D], [Correct Answer] AS Correct_Answer FROM [QuizData]">
</asp:AccessDataSource>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
In Button1_Click on your codebehind you can improve this method:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS.Checked)
{
Insert(rd_CS.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS2.Checked)
{
Insert(rd_CS2.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS3.Checked)
{
Insert(rd_CS3.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS4.Checked)
{
Insert(rd_CS4.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
}
}
And the Insert function definition will be same as:
private void Insert(string value)
{
//Your code here to save on database
OleDbConnection connection = new OleDbCommand("Your sql connection String");
OleDbCommand command = new OleDbCommand("Your sql insert query");
command.Connection = connection;
//ParĂ¡meters of command
OleDbParameter param = new OleDbParameter("Parameter name and next your type", OleDbType.VarChar);
param.Value = value;
command.Parameters.Add(param);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
//Your value is saved now
}
This is how you can save all checked radiobutton on datalist you asked
This is my codebehind .When i click on button then Repeated selected radio button values are save in my database . this is my problem. I need only unique value in my database
protected void rd_CS_CheckedChanged(object sender, EventArgs e)
{
string myRadioText = String.Empty;
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS != null && rd_CS.Checked)
{
myRadioText = rd_CS.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS2 != null && rd_CS2.Checked)
{
myRadioText = rd_CS2.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS3 != null && rd_CS3.Checked)
{
myRadioText = rd_CS3.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS4 != null && rd_CS4.Checked)
{
myRadioText = rd_CS4.Text;
Label1.Text = myRadioText.ToString();
}
string str = Server.MapPath("~/App_Data/Quize.mdb");
OleDbConnection ole = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str + ";Persist Security Info=True");
ole.Open();
OleDbCommand cmd = new OleDbCommand("insert into Userdata values ('" + Label1.Text.Trim().Replace("'", "''") + "','" + Label1.Text.Trim().Replace("'", "''") + "',)", ole);
cmd.ExecuteNonQuery();
}
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();
}
Hi I have a problem with my code, I am implementing a rating application. I have connected a access database to my website. I then added in the ajax control and gridview etc..
this is my code so far..
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<asp:GridView ID="gvwMake" runat="server" DataKeyNames="MachineID"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" AllowPaging="True"
OnSelectedIndexChanged="gvwMake_SelectedIndexChanged">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
<Columns>
<asp:BoundField DataField="Make" HeaderText="Make" />
<asp:ImageField DataImageUrlField="Image"></asp:ImageField>
<asp:TemplateField HeaderText="Machine Rating">
<ItemTemplate>
<cc1:Rating ID="Rating1"
AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar"
EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar"
CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
That all seems to be working fine however the problem is with the code behind.
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
public partial class rate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = MachineClass.getMachine();
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
}
protected void gvwMake_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwMake.PageIndex = e.NewPageIndex;
DataSet ds = MachineClass.getMachine();
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
protected void gvwMake_SelectedIndexChanged(object sender, EventArgs e)
{
string strID = gvwMake.SelectedRow.Cells[2].Text;
Session["TID"] = strID;
Response.Redirect("~/Result.aspx");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DataSet ds = MachineClass.getMachine(txtSearch.Text);
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
private void ShowData()
{
using (OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT TOP 20 Products.ProductID, Products.ProductName," +
" Products.UnitPrice, Products.SupplierID, " +
"Products.CustomerRating FROM Products",
new OleDbConnection(
ConfigurationManager.ConnectionStrings["comac.mdb.accdb"].ToString())))
{
DataTable dt = new DataTable();
da.SelectCommand.Connection.Open();
da.Fill(dt);
this.gvwMake.DataSource = dt;
this.gvwMake.DataBind();
}
}
protected void Rating1_Changed(object sender,
AjaxControlToolkit.RatingEventArgs e)
{
AjaxControlToolkit.Rating myRating =
(AjaxControlToolkit.Rating)sender;
System.Text.RegularExpressions.Regex rexLineNo =
new System.Text.RegularExpressions.Regex("ctl\\d+");
this.updateRating(this.MachineId(
rexLineNo.Match(myRating.UniqueID).ToString()), e.Value);
}
private string MachineId(string LineNo)
{
foreach (GridViewRow r in this.gvwMake.Rows)
{
Label lblMachineId = (Label)r.FindControl("lblMachineId");
if (lblMachineId.UniqueID.Contains(LineNo))
{
return lblMachineId.Text;
}
}
return string.Empty;
}
private void updateRating(string MachineId, string Rating)
{
OleDbParameter paramRating = new OleDbParameter("#Rating", Rating);
OleDbParameter paramMachineId =
new OleDbParameter("#MachineId", MachineId);
using (OleDbCommand cmd = new OleDbCommand(
"UPDATE Machines SET CustomerRating " +
"= #Rating WHERE Machines.MachineID=#MachineId",
new OleDbConnection(
ConfigurationManager.ConnectionStrings["comac.mdb.accdb"].ToString())))
{
cmd.Parameters.Add(paramRating);
cmd.Parameters.Add(paramMachineId);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
This is my first time using the ajax rating control and not sure if the codes suitable for it when i run the webpage i get an error message
'ASP.rate_aspx' does not contain a definition for 'OnRatingChanged' and no extension method 'OnRatingChanged' accepting a first argument of type 'ASP.rate_aspx' could be found (are you missing a using directive or an assembly reference?)
What I could see from the below part of your code:
<ItemTemplate>
<cc1:Rating ID="Rating1"
AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar"
EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar"
CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>
is the place where you use the Rating Control, you are assigning OnChanged Event to a Code behind method OnRatingChanged (mentioned as OnChanged="OnRatingChanged"in your code) and since your code behind does not have any method named OnRatingChanged the error is thrown saying 'ASP.rate_aspx' does not contain a definition for 'OnRatingChanged'.
So if you are really not using this event then remove the event (remove the part: OnChanged="OnRatingChanged" from your code) or in case if you are using this then include an appropriate 'OnRatingChanged' method in your code behind.
Okay here is the C# code. You will have to import the following namespaces:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
//the page_onload add the following code
if (!IsPostBack)
{
gvFruits.DataSource = GetData("SELECT FruitId, FruitName, ISNULL((SELECT AVG(Rating) FROM Fruit_Ratings WHERE FruitId = Fruits.FruitId), 0) Rating FROM Fruits");
gvFruits.DataBind();
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
//and here is the code full functioning app for rating.[Full functioning rating app code][1]
[1]: http://www.aspsnippets.com/Articles/Using-ASPNet-AJAX-Rating-Control-inside-GridView-TemplateField-ItemTemplate.aspx
Okay Try the demo from this website probably you will find it usefull>
http://www.aspsnippets.com/Articles/Using-ASPNet-AJAX-Rating-Control-inside-GridView-TemplateField-ItemTemplate.aspx
first add ajax toolkit from your ajax toolbox and then apply followin coding with css.
<style type="text/css">
.Star
{
background-image: url(Images/rsz_star-deselect.png);
height: 17px;
width: 17px;
}
.WaitingStar
{
/*background-image: url(images/WaitingStar.gif);*/
height: 17px;
width: 17px;
}
.FilledStar
{
background-image: url(Images/rsz_star-select.png);
height: 17px;
width: 17px;
}
</style>
<ItemTemplate>
<cc1:Rating ID="Rating1" AutoPostBack="true" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar" CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>
I'm trying to make my gridview sortable. I have allow sorting and added a onsorting attribute given below
<asp:GridView ID="GWCase" runat="server" DataKeyNames="detail, propertydetail,suspectdetail " BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" Width="100%" AutoGenerateSelectButton="True" OnSelectedIndexChanged="GWCase_SelectedIndexChanged" AutoGenerateColumns="False" AllowPaging="True" PageSize="5" OnPageIndexChanging="GWCase_PageIndexChanging" AllowSorting="True" OnSorting="gridView_Sorting" CurrentSortField="memberreportid" CurrentSortDirection="ASC">
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:BoundField DataField="memberreportid" HeaderText="MemberReportID" SortExpression="memberreportid"/>
<asp:BoundField DataField="typeofcrime" HeaderText="Type of Crime" SortExpression="typeofcrime" />
<asp:BoundField DataField="crdatetime" HeaderText="ReportDateTime" SortExpression="crdatetime" />
<asp:BoundField DataField="address" HeaderText="Address" SortExpression="address" />
<asp:BoundField DataField="incidentdate" HeaderText="Incident Date" SortExpression="incidentdate" />
<asp:BoundField DataField="incidenttime" HeaderText="Incident Time" SortExpression="incidenttime"/>
<asp:BoundField DataField="property" HeaderText="Property" SortExpression="Property"/>
<asp:BoundField DataField="victim" HeaderText="Victim" SortExpression="victim" />
<asp:BoundField DataField="suspect" HeaderText="Suspect" SortExpression="suspect"/>
<asp:BoundField DataField="detail" HeaderText="Detail" SortExpression="detail" Visible="false"/>
</Columns>
</asp:GridView>
This is my c# code i used to enable the sorting
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection sortDirection = SortDirection.Ascending;
string sortField = string.Empty;
SortGridview((GridView)sender, e, out sortDirection, out sortField);
string strSortDirection = e.SortDirection == SortDirection.Ascending ? "ASC" : "DESC";
//Error happens here
GWCase.DataSource = (e.SortExpression + " " + strSortDirection);
GWCase.DataBind();
}
private void SortGridview(GridView gridView, GridViewSortEventArgs e, out SortDirection sortDirection, out string sortField)
{
sortField = e.SortExpression;
sortDirection = e.SortDirection;
if (gridView.Attributes["CurrentSortField"] != null && gridView.Attributes["CurrentSortDirection"] != null)
{
if (sortField == gridView.Attributes["CurrentSortField"])
{
if (gridView.Attributes["CurrentSortDirection"] == "ASC")
{
sortDirection = SortDirection.Descending;
}
else
{
sortDirection = SortDirection.Ascending;
}
}
gridView.Attributes["CurrentSortField"] = sortField;
gridView.Attributes["CurrentSortDirection"] = (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
}
The tutorial i follow required a data layer which i didnt use as i have binded my gridview with boundfield. However when trying to get my datasource they gave me the error stated above.
This is how i bind my gridview
private void LoadGrid()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI";
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT memberreportid, typeofcrime, crdatetime, address, detail, incidentdate, incidenttime, property, victim, suspect, detail, suspectdetail, propertydetail from memberreport where assignto = 'unassign'", conn);
da.Fill(ds);
GWCase.DataSource = ds.Copy();
GWCase.DataBind();
conn.Close();
}
Your problem is the following line of code:
GWCase.DataSource = (e.SortExpression + " " + strSortDirection);
This is telling the GridView to bind to something that is not the same type of data source you originally bound the grid to. For example, if the user had selected to sort by clicking the Victim column, then the above code would try to set a string of victim ascending as the data source, which clearly is incorrect.
To get quick paging/sorting capabilities into a GridView the easiest way is to use the DataTable data structure, along with a DataView data structure.
A previous StackOverflow question details an example of doing this. The question itself details the usage of DataTable and DataView to facilitate the sorting and paging, along with using ViewState to maintain whether the sorting direction is ascending or descending.
Read Enable Sorting and Paging in Gridview Efficiently to see the code example.
To more appropriately handle paging/sorting, you would want to incorporate custom paging and sorting instead of the AllowPaging=True and AllowSorting=True settings on the GridView. The reason for this is that those GridView settings still ask for all of the rows from whatever data source you are using (usually a database) and loads it all into memory, which if it is 20 rows that is not so bad, but imagine 10,000 rows of data; it will be slow and inefficient use of memory. True paging will only get the exact amount of rows to show on the page and then ask for another page chunk when the user navigates; it is more chatty with calling the database more than once, but it is extremely fast and efficient memory-wise.