I am trying to make the upload control upload multiple files, but it is only uploading one and I am not sure why. Also I want to call the stored proc if, and only if, all required files have successfully been uploaded. Any suggestions would be helpful as I am at a loss. im sure its something im doing wrong within my foreach loop but I am unsure what exactly it is.
My markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addFont.aspx.cs" Inherits="Admin_addFont" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Fonts</h1>
<h2>Currently available fonts</h2>
<div><asp:Label ID="lblFontGrd" runat="server"></asp:Label>
<asp:GridView ID="grdFonts" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnPageIndexChanging="grdFonts_PageIndexChanging">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="ID" FooterText="ID" HeaderText="ID">
<ItemTemplate>
<asp:Label ID="fontId" runat="server" Text='<%# Eval("FontId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Font Name" FooterText="Font Name" HeaderText="Font Name">
<ItemTemplate>
<asp:Label ID="lblfontName" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblfontNameEdit" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Example" FooterText="Example" HeaderText="Example">
<ItemTemplate>
<asp:Label id="lblfontExample" runat="server" Font-Size="Large" Font-Names='<%# BuildFont(Eval("FontFamily").ToString()) %>' ><h3>This is an example of the font</h3></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Discontinued?" HeaderText="Discontinued?" FooterText="Discontinued?">
<ItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<span onclick="return confirm('Are you sure you want to delete?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</div>
<div>
<h2>Add a new font</h2>
<asp:Label ID="lblUpload" runat="server" ForeColor="Red"></asp:Label>
<p>In order to add a new font to the library please follow the steps laid out below:</p>
<p><strong>Step 1: </strong> The first, and most important, thing to do is make sure you have the appropriate license to use your font for print and web.</p>
<p><strong>Step 2: </strong> Next you need to convert your font file into multple formats to ensure browser compatability.
To do so please follow <a target="_blank" href="http://www.fontsquirrel.com/tools/webfont-generator">this</a> link.
Select OPTIMAL and upload your file. Unzip the files generated by the tool.</p>
<p><strong>Step 3: </strong> Now you need open the file that ends with '.css', a simple text editor such as notepad will do just fine.</p>
<p><strong>Step 4: </strong> Find the font-family property(see image below)</p><br />
<asp:Image ID="imgFontCssEx" runat="server" ImageUrl="~/Images/fontCssImg.png" /><br />
<p><strong>Step 5: </strong> Make sure you copy the font-family value exactly as shown in the css into the text box below, marked Font Name.</p>
<asp:TextBox ID="txtFontFam" runat="server"></asp:TextBox>
<asp:Label ID="lblFontFam" runat="server" Text="Font Family"></asp:Label>
<br />
<p><strong>Step 6: </strong> Enter a display name for your font.</p>
<asp:TextBox ID="txtFontName" runat="server"></asp:TextBox>
<asp:Label ID="lblFontName" runat="server" Text="Display Name" ></asp:Label>
<br />
<p><strong>Step 7: </strong> Now you need to upload the files specified below:</p><br />
<asp:FileUpload ID="flupFonts" runat="server" AllowMultiple="true" />
<asp:Label ID="lblCss" runat="server" AssociatedControlID="flupFonts" Text="Upload file with files ending: .css, .ttf, .svg, .eot, .woff, .woff2"></asp:Label>
<p><strong>Finally: </strong> Click the button below and the font will be made available.</p>
<br />
<asp:Button ID="btnUploadFont" runat="server" Text="Add Font" OnClick="btnUploadFont_Click" />
</div>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Admin_addFont : System.Web.UI.Page
{
private string fontUploadDirectory;
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define parameters
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
// attempt to connect to db, read data, fill dataset and bind gridview. Catch exceptions and close the connection.
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
grdFonts.DataSource = ds;
grdFonts.DataBind();
}
catch (Exception err)
{
lblFontGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdFonts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdFonts.PageIndex = e.NewPageIndex;
BindGrid();
}
public static string[] BuildFont(string font)
{
string[] array = new string[1];
array[0] = font;
return array;
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { "eot", "ttf", "svg", "woff", "woff2", "css" };
bool isValidFile = false;
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
if (fileCollection.Count == 6)
{
string serverFileName = Path.GetFileName(flupFonts.PostedFile.FileName);
string ext = Path.GetExtension(serverFileName).ToLower();
string fullUploadPath = Path.Combine(fontUploadDirectory, serverFileName);
try {
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
if (!File.Exists(fullUploadPath))
{
try
{
flupFonts.PostedFile.SaveAs(fullUploadPath);
break;
}
catch (Exception err)
{
lblUpload.Text = err.Message;
}
}
}
}
if (!isValidFile)
{
lblUpload.Text += "Invalid File. Please upload a File with extension " + string.Join(",", validFileTypes);
}
}
fontDbInfo();
BindGrid();
}
catch (Exception err)
{
lblUpload.Text = "Error: " + err.Message;
}
}
else
{
if (fileCollection.Count < 6)
{
lblUpload.Text = "Please make sure you select all required files.";
}
if (fileCollection.Count > 6)
{
lblUpload.Text = "You have selected too many files. Please only add the required files.";
}
}
}
}
protected void fontDbInfo()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Add";
cmd.Parameters.Add(new SqlParameter("#FontName", SqlDbType.VarChar, 50));
cmd.Parameters["#FontName"].Value = txtFontName.Text;
cmd.Parameters.Add(new SqlParameter("#FontFamily", SqlDbType.VarChar, 50));
cmd.Parameters["#FontFamily"].Value = txtFontFam.Text;
cmd.Parameters.Add(new SqlParameter("#Discontinued", SqlDbType.Bit));
cmd.Parameters["#Discontinued"].Value = 0;
// try to open database, insert font info, catch errors and close the connection
try
{
con.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
}
catch (Exception err)
{
lblFontGrd.Text = "Error: " + err.Message;
}
finally
{
con.Close();
}
}}
my stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Fonts]
-- Add the parameters for the stored procedure here
#Status varchar(50) = '',
#FontId tinyint = '',
#FontName varchar(50) = '',
#FontFamily varchar(50) = '',
#Discontinued bit = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select FontId, FontName, FontFamily, Discontinued
from ProductDetails.Fonts
where Discontinued = 0
order by FontName asc
end
if (#Status = 'FontFam')
begin
select FontFamily from ProductDetails.Fonts
where FontId = #FontId
end
if (#Status = 'Add')
begin
insert into ProductDetails.Fonts (FontName, FontFamily, Discontinued)
values (#FontName, #FontFamily, #Discontinued)
end
if (#Status = 'Delete')
begin
UPDATE ProductDetails.Fonts
SET Discontinued = #Discontinued
where FontId = #FontId
end
END
I think the way you are attempting to loop through the HttpPostedFile collection is causing you problems. Try checking file validity in a separate method. I'd also suggest you break this problem down into pieces you can test. For example, try a simple Test page with code something like this. Hope this helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Test : System.Web.UI.Page
{
private string fontUploadDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { ".eot", ".ttf", ".svg", ".woff", ".woff2", ".css" };
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
string ext = System.IO.Path.GetExtension(uploadedFont.FileName);
if (isValid(uploadedFont, validFileTypes, ext))
{
uploadedFont.SaveAs(fontUploadDirectory + "\\" + System.IO.Path.GetFileName(uploadedFont.FileName));
}
}
}
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext)
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
}
Replace this loop:
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
...
}
With this:
foreach(string key in flupFonts.Keys)
{
HttpPostedFile uploadedFont = flupFonts[key];
...
}
Related
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();
}
Greetings to all
Actually i'm developing a web application Which will generate DataGrid,Button and a Label at run time depends upon the value return from database.
Eg:
if return value is 2 then the 3 controls(datagrid,button and label) will generate twice.like shown below
Application working Procedure is.On click on search button the above 3 controls are generated and bind the datagrid.I have achieved this using repeater.
Now what i need is....inside that datagrid i have a button called refresh.When the Refresh button is clicked the gross weight and volume in the datagrid should display the string value,remaining columns should not get change.
Here is my aspx code:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server"
Text="<%#Container.DataItem%>"></asp:Label>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/>
<br />
<asp:DataGrid ID="dgLCL" runat="server" AutoGenerateColumns="False"
ShowFooter="FALSE" CellPadding="3" OnItemCommand="dgLCL_Select"
OnDeleteCommand="dgLCL_Delete">
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type">
</asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete"
ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem"
OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Add">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd"
ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="InsertItem"
AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White"
Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
and my code behind is:
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string Flag = Session["Flag"].ToString();
if (Flag=="B")
{
e.Item.FindControl("textBoxSearch").Visible = false;
e.Item.FindControl("BTNAdd").Visible = false;
}
DataGrid gv = e.Item.FindControl("dgLCL") as DataGrid;
//
Label label = e.Item.FindControl("textBoxSearch") as Label;
Session["Label"] = label.Text;
Session["FlagB"] = Flag;
Session["GV"] = gv;
gridbind(label.Text, Flag, gv);
}
void gridbind(string label,string Flag,DataGrid gv)
{
try
{
if (Session["Loading"] != null)
{
PortLName.Text = Session["Loading"].ToString();
}
if (Session["Destination"] != null)
{
PortDName.Text = Session["Destination"].ToString();
}
string SFRID = label;
if (Flag == "L")
{
sql = "Select MasterNo , MasterDate,GrossWt,GrossUOMType,Volume,tBLg_NUPKId from VW_TransLCLMaster where tBLG_mDOC_NUPKID ='107' and tBLG_NUIsActive=1 and PortOfDischargeName='" + SFRID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (gv != null)
{
gv.DataSource = ds;
gv.DataBind();
}
}
}
catch (Exception ex)
{
}
as shown in above image i need the string values should assign to grosswt and volume on refresh button click.
Please help me thanks in advance.
In your datagrid columns add another column
<asp:TemplateColumn HeaderText="Refresh">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNRefresh"
ImageUrl="~/AppImages/grid-icon-refresh.jpg"
ToolTip="Insert" CommandName="Refresh"
AlternateText="Refresh" />
</ItemTemplate>
</asp:TemplateColumn>
In your DagaGrid's OnItemCommand event, set the text for both the cells as below
protected void dgLCL_Select(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Refresh")
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Change the indexes to correct column index
e.Item.Cells[3].Text = "your dynamic gross weight text";
e.Item.Cells[5].Text = "your dynamic volumne text";
}
}
}
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>
Or maybe I don't need to, I don't know. Here's what I'm trying to do. I have a gridview on one page and when I click on an item, it takes the ID and links it to another page that displays all the info that goes with the item in the gridview. On the second page, I want to be able to insert a photo with some text into my database, but I want to make sure it inserts with the proper blogID (that was clicked on from the first page). Here's my code so far:
EditBlogPosts.aspx
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateEditButton="True"
DataSourceID="AccessDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID"
AlternatingRowStyle-BackColor="Gray"
AlternatingRowStyle-CssClass="editGridFormat" RowStyle-CssClass="editGridFormat"
RowStyle-VerticalAlign="Top"
onselectedindexchanged="GridView1_SelectedIndexChanged">
Code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Redirect("~/EditThisPost.aspx?ID=" + row.Cells[2].Text);
}
EditThisPost.aspx
<asp:FormView ID="Formview1" runat="server" DefaultMode="Insert" DataSourceID="AccessDataSource1" >
<InsertItemTemplate>
<br />
<asp:Label ID="TextforPhotoLabel" runat="server" Text="Put your text to go with your photo here:" /><br />
<asp:TextBox ID="PhotoText" runat="server" Rows="10" Columns="100" /><br /><br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="UploadStatusLabel" runat="server" Text="Status: " /><br />
<asp:Button ID="UploadButton" runat="server" OnClick="UploadFile" Text="Insert Item" /><br />
</InsertItemTemplate>
</asp:FormView>
Code behind (paying special attention to the line where I declare int blogID):
protected void UploadFile(object sender, EventArgs e)
{
TextBox txtPhotoText = (TextBox)Formview1.FindControl("PhotoText");
FileUpload FileUpload1 = (FileUpload)Formview1.FindControl("FileUpload1");
Label UploadStatusLabel = (Label)Formview1.FindControl("UploadStatusLabel");
if (FileUpload1.HasFile)
{
try
{
if (FileUpload1.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload1.PostedFile.ContentLength < 10240000)
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/photos/PeoplePhotos/") + filename);
UploadStatusLabel.Text = "Upload status: Complete!";
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO BlogEntryItems (BlogID, Picture, PicText1) VALUES (?,?,?)";
int blogID = int.Parse(Request.QueryString["ID"]);
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#BlogID", blogID);
com.Parameters.AddWithValue("#Picture", filename);
com.Parameters.AddWithValue("#PicText1", txtPhotoText);
com.ExecuteNonQuery();
con.Close();
}
else
UploadStatusLabel.Text = "Upload status: The file has to be less than 10 MB!";
}
else
UploadStatusLabel.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
UploadStatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I truly appreciate any help. I was thinking I could somehow get the ID that was passed to make the "~\EditThisPost.aspx?ID=" a valid link. But if there is a better way to do it or if the way I'm thinking doesn't even exist, then how can I accomplish what I need?
you can get the blogID as below
int blogID = int.Parse(Request.QueryString["ID"]);
I would use int.TryParse to avoid exceptions in case of non integer values in the query string
int blogID;
int.TryParse(Request.Querystring["ID"], out blogID);
add a Viewstate-backed property to EditThisPost.aspx to hold BlogID: -
http://www.codingwith.net/2008/01/viewstate-backed-properties-part-one.html
Set this property in PageLoad of EditThisPost.aspx, and then use it in UploadFile.
I am creating the update button for the cart system in asp.net. What am I trying to do is to allow user key in the quantity items and then click the update button. Here is the design of the shopping cart system...
Unfortunately the update button doesn't work properly after the first row. I have debugged the problem and the for loop inside the btn_update_Click method returns the value of zero.
Is there any other way to overcome the problem? Thanks
Here is the source code:
<b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b>
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'>
<img src='<%#Eval("image") %>' />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productname" Text='<%# Eval("product_name") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_productQuantity" Text='<%# Eval("product_quantity") %>' CssClass="form-control" runat="server" Width="60" MaxLength="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" OnClick="btn_update_Click" />
<asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-danger" onclick="btn_remove_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productcost" Text='<%#"$"+Eval("product_cost") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sds_store" runat="server"
ConnectionString="<%$ ConnectionStrings:websiteConnection %>"
SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = #username AND [visible] = #visible">
<SelectParameters>
<asp:sessionparameter sessionfield="login" Name="username" />
<asp:Parameter Name="visible" Type="string" DefaultValue="true" />
</SelectParameters>
</asp:SqlDataSource>
<h4><asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"></asp:Label></h4>
<br /><br /><br />
<asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" />
Here's another source code for the .cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace websiteEcom
{
public partial class cart : System.Web.UI.Page
{
// Open the connection for the sql
private static SqlConnection conn;
private static SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
// Create an instance for the connection of database
string connectionString = ConfigurationManager.ConnectionStrings["websiteConnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
// Checks how many items are there inside the cart database and display it to the label
CheckHowManyItem();
// Multiply all the sums of the cost
lbl_totalCost.Text = "Total Cost: $"+TotalProductCost().ToString();
}
// Checks how many items are there inside the cart database and display it to the label
public void CheckHowManyItem()
{
try
{
conn.Open();
// Retrieve the number of rows from the database
string query = string.Format("SELECT COUNT(*) FROM tbl_cart WHERE name = '{0}' AND visible = '{1}'", Session["login"], "true");
command.CommandText = query;
int numberOfItems = (int)command.ExecuteScalar();
// If the number of rows is zero
if (numberOfItems == 0)
{
lbl_showResult.Text = "You have no items inside the cart.";
btn_buy.Visible = false;
}
else
{
// If there is number of rows inside
lbl_showResult.Text = "There are currently " + numberOfItems + " inside the cart.";
btn_buy.Visible = true;
}
}
finally
{
conn.Close();
}
}
protected void btn_remove_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
try
{
conn.Open();
// Make the cart invisible if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET visible = '{0}' WHERE id = '{1}'", "false", btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
// Multiply all the values of purchases together
public int TotalProductCost()
{
int totalCost = 0;
int currentCost = 0;
int currentQuantity = 0;
for (int i = 0; i < grv_cart.Rows.Count; i++)
{
// Get the data values from the forms
HyperLink hypCost = (HyperLink)grv_cart.Rows[i].Cells[0].FindControl("hyp_productcost");
TextBox txtQuantity = (TextBox)grv_cart.Rows[i].Cells[0].FindControl("txt_productQuantity");
// Sum the product quantity and the product cost
// Attempt to parse your value (removing any non-numeric values)
currentQuantity = Int32.Parse(Regex.Replace(txtQuantity.Text, #"[^\d]", ""));
// Attempt to parse your value (removing any non-numeric values)
currentCost = Int32.Parse(Regex.Replace(hypCost.Text, #"[^\d]", ""));
currentCost *= currentQuantity;
totalCost += currentCost;
}
return totalCost;
}
protected void btn_buy_Click(object sender, EventArgs e)
{
}
protected void btn_update_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
foreach (GridViewRow grvCart in grv_cart.Rows)
{
Debug.WriteLine(btn.CommandArgument);
TextBox textQuantity = (TextBox)grvCart.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
}
}
}
Try using the RowCommand event (especially since you already have the CommandArgument set up). That is the more appropriate way to handle this type of action (and that way you can just update one row at a time, without looping through all of them).
Handle the RowCommand event in your GridView declaration:
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True"
GridLines="None" CssClass="table" OnRowCommand="grv_cart_RowCommand">
And then your event handler would look like this:
protected void grv_cart_RowCommand(Object sender, GridViewCommandEventArgs e)
{
GridViewRow rowToUpdate = grv_cart.Rows[Int.Parse(e.CommandArgument)];
TextBox textQuantity = (TextBox)rowToUpdate.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, e.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
Note: You'll want to remove the OnClick handler from the update button:
<asp:Button ID="btn_update" Text="Update" runat="server"
CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" />