Hi all im new to the site and have a question to do with c# in asp.net. i have made a website using HTML5 markup and CSS in asp.net with c# for the code behind. The issue im having is i made a index.aspx page with c# code behind to show all my products in a panel which are retrieved directly from the image folder using the Fillpage method. The problem i have is im not sure how to add alt tags to the images as i don't actually see the images until i run my site in the browser. I tested my site for accessibility and it showed the missing alt tag error. Can anyone give me some advice on how to add the alt tags to the images please?
Thank you.
index.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Fillpage();
}
private void Fillpage()
{
//Retrieve list of all products in the database
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetAllProducts();
//check products exist in the database
if (products !=null)
{
//create a new panel with an imagebutton and 2 labels for each product
foreach (Product product in products)
{
Panel productPanel = new Panel();
ImageButton imageButton = new ImageButton();
Label lblName = new Label();
Label lblPrice = new Label();
//Set childControls properties
imageButton.ImageUrl = "~/Images/Products/" + product.Image;
imageButton.CssClass = "productImage";
imageButton.PostBackUrl = "~/pages/Product.aspx?id=" + product.ID;
lblName.Text = product.Name;
lblName.CssClass = "productName";
lblPrice.Text = "£" + product.Price;
lblPrice.CssClass = "productPrice";
//Add childControls to the panel
productPanel.Controls.Add(imageButton);
productPanel.Controls.Add(new Literal{Text = "<br />"});
productPanel.Controls.Add(lblName);
productPanel.Controls.Add(new Literal{Text = "<br />"});
productPanel.Controls.Add(lblPrice);
//Add dynamic paneld to static parent panel
pnlProducts.Controls.Add(productPanel);
}
}
else
{
//no products found
pnlProducts.Controls.Add(new Literal {Text = "No Products found!"});
}
}
}
product.aspx.cs
using System;
using System.Linq;
using Microsoft.AspNet.Identity;
public partial class Pages_Product : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string clientId = Context.User.Identity.GetUserId();
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
int amount = Convert.ToInt32(ddlAmount.SelectedValue);
Cart cart = new Cart
{
Amount = amount,
ClientID = clientId,
DatePurchased = DateTime.Now,
IsInCart = true,
ProductID = id
};
CartModel model = new CartModel();
lblResult.Text = model.InsertCart(cart);
}
else
{
lblResult.Text = " Please log in to order products ";
}
}
}
private void FillPage()
{
//Get selected product data
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
int id = Convert.ToInt32(Request.QueryString["id"]);
ProductModel model = new ProductModel();
Product product = model.GetProduct(id);
//Fill page with data
lblTitle.Text = product.Name;
lblDescription.Text = product.Description;
lblPrice.Text = "Price per unit:<br/>£ " + product.Price;
imgProduct.ImageUrl = "~/Images/Products/" + product.Image;
lblItemNr.Text = product.ID.ToString();
//Fill amount list with numbers 1-20
int[] amount = Enumerable.Range(1, 20).ToArray();
ddlAmount.DataSource = amount;
ddlAmount.AppendDataBoundItems = true;
ddlAmount.DataBind();
}
}
}
Use imageButton.AlternateText property.
Related
Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);
I'm quite new to ASP.NET and I need your help.
I'm programming on an application which should help to fix frequent issues. Users can click the displayed cases if it describes their problem. The application searches for more cases or displays a possible solution.
Now what I need for this is some code which creates the buttons dynamically. I googled some ideas and created some code, however I was not able to get it to work.
It works to create the first selection of buttons with the Default_Load method. Also the OnClick event (ButtonClick_System) works fine which means I get the next selection.
From here it starts messing around. The dynamic buttons created in ButtonClick_System don't have a working OnClick action.
Instead of proceeding with ButtonClick_Question (because of btn_system.Command += ButtonClick_Question; in ButtonClick_System) it seems like it just loads the homepage (maybe something wrong with Page_Load?).
The application should do ButtonClick_Question until no more datasets available in database.
I got the following code:
using System;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using Oracle.DataAccess.Client;
namespace Application
{
public partial class _default : System.Web.UI.Page
{
// Variables
private string app_name = "Application";
// ----- Page_Load ----- //
protected void Page_Load(object sender, EventArgs e)
{
Default_Load();
Session["Application"] = app_name;
}
// ----- Methods ----- //
// Load homepage
public void Default_Load()
{
pnl_default.Visible = true;
pnl_content.Visible = false;
HtmlGenericControl html_default = new HtmlGenericControl();
html_default.TagName = "div";
string cmdString = "(...)";
DataTable dtSystems = OraQueryData(cmdString);
foreach (DataRow dtRow in dtSystems.Rows)
{
int system_id = Convert.ToInt32(dtRow["SYSTEM_ID"]);
string system_name = Convert.ToString(dtRow["SYSTEM_NAME"]);
var btn_system = new Button
{
ID = "btn_" + system_name,
Text = system_name,
CssClass = "sys_buttons"
};
btn_system.Command += ButtonClick_System;
btn_system.CommandArgument = Convert.ToString(system_id);
html_default.Controls.Add(btn_system);
}
plh_default.Controls.Clear();
plh_default.Controls.Add(html_default);
}
// Button OnClick Events
protected void ButtonClick_System(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_questions = new HtmlGenericControl();
html_questions.TagName = "div";
int system_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = Convert.ToString(system_id);
html_questions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_questions);
}
protected void ButtonClick_Question(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_ChildQuestions = new HtmlGenericControl();
html_ChildQuestions.TagName = "div";
int parent_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtChildQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtChildQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = question_id;
html_ChildQuestions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_ChildQuestions);
}
// ----- Oracle Data Query Methods ----- //
// Create and execute query on database
public static DataTable OraQueryData(string cmdString)
{
string conString = ConfigurationManager.AppSettings["Connection"];
OracleConnection oraCon = new OracleConnection(conString);
OracleCommand oraCmd = new OracleCommand(cmdString, oraCon);
OracleDataAdapter oraDtAd = new OracleDataAdapter(oraCmd.CommandText, oraCon);
DataTable dt = new DataTable();
oraCon.Open();
oraDtAd.Fill(dt);
oraCon.Close();
return dt;
}
}
}
If I've understood the issue correctly I think you're using the wrong controls for the wrong usages.
What I'd suggest you need to do is bind the collection of FAQ records to a repeater or some other data set display control. You can then have an event on the repeater which can handle which record ID has been clicked, post back with that value and refresh the collection of data from that (maybe in another repeater). Don't dynamically create buttons and bind events to them otherwise you will end up in a mess.
Hope this helps.
I have the following code which populates an html table from data retrieved from Parse.com.
As you can see the table has buttons in it which are generated as the table gets populated. When clicked, obviously the buttons need to perform an action related to that row of data.
Can anybody help me with the click event please, specifically getting the row index?
At the moment the click event doesn't even seem to trigger the "response.Write" alert. (i'm very new to asp.net though)
using Parse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace FrogPointCMS
{
public partial class Beacons : System.Web.UI.Page
{
string merchantName;
string myMerchantID;
ParseObject merchantObject;
protected void Page_Load(object sender, EventArgs e)
{
merchantName = Request.QueryString["user"];
myMerchantID = Request.QueryString["merchantID"];
merchantObject = (ParseObject)Session["Merchant"];
getBeacons();
}
public async void getBeacons()
{
MyParseQueries myQuery = new MyParseQueries();
var myBeacons = await myQuery.getMyBeacons(merchantObject);
foreach (ParseObject beacon in myBeacons)
{
string aliasName = "";
string offerType = "N/A";
string offerTitle = "";
string offerDescription = "";
var merchantOb = beacon.Get<ParseObject>("merchantObjectId");
var merchantID = merchantOb.ObjectId;
if (merchantID == myMerchantID)
{
if (beacon.ContainsKey("contentObjectID"))
{
ParseObject content = beacon.Get<ParseObject>("contentObjectID"); // get the content object from parse.
offerType = content.Get<string>("offerType");
offerTitle = content.Get<string>("offerTitle");
offerDescription = content.Get<string>("offerDescription");
}
aliasName = beacon.Get<string>("aliasName");
Button assignNameBtn = new Button();
assignNameBtn.ID = "assignName";
assignNameBtn.Text = "Assign Name";
assignNameBtn.Click += assignNameBtn_Click;
Button assignActionBtn = new Button();
assignActionBtn.ID = "assignAction";
assignActionBtn.Text = "Assign Action";
var tr = new HtmlTableRow();
var checkBox = new HtmlTableCell();
var tableCellName = new HtmlTableCell();
var tableCellButton1 = new HtmlTableCell();
var tableCellButton2 = new HtmlTableCell();
var tableCellAction = new HtmlTableCell();
checkBox.InnerHtml = "<input type=\"checkbox\"/>";
tableCellName.InnerText = aliasName;
tableCellButton1.Controls.Add(assignNameBtn);
tableCellButton2.Controls.Add(assignActionBtn);
tableCellAction.InnerText = offerType + " - " + offerTitle + " - " + offerDescription;
tr.Cells.Add(checkBox);
tr.Cells.Add(tableCellName);
tr.Cells.Add(tableCellButton1);
tr.Cells.Add(tableCellAction);
tr.Cells.Add(tableCellButton2);
beaconTable.Rows.Add(tr);
}
}
}
void assignNameBtn_Click(object sender, EventArgs e)
{
Response.Write("<script type=\"text/javascript\">alert('Button clicked');</script>");
var btn = (Button)sender; // testing
HtmlTableRow row = (HtmlTableRow)btn.NamingContainer; //testing
}
}
}
If you want to do javascript stuff when clicking a button, use OnClientClick
Button b = new Button();
b.OnClientClick = "FunctionName"
And then in the html
<script>
function FunctionName() {
alert('Button clicked');
}
</script>
I'm using PostBackUrl to post my control from a "firstwebpage.aspx" to a "secondwebpage.aspx" so that I would be able to generate some configuration files.
I do understand that I can make use of PreviousPage.FindControl("myControlId") method in my secondwebpage.aspx to get my control from "firstwebpage.aspx"and hence grab my data and it worked.
However, it seems that this method does not work on controls which I generated programmically during runtime while populating them in a table in my firstwebpage.aspx.
I also tried using this function Response.Write("--" + Request["TextBox1"].ToString() + "--");
And although this statement do printout the text in the textfield on TextBox1, it only return me the string value of textbox1. I am unable to cast it to a textbox control in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
My question is, how can I actually access the control which i generated programmically in "firstwebpage.aspx" on "secondwebpage.aspx"?
Please advice!
thanks alot!
//my panel and button in aspx
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Generate Xml" PostBackUrl="~/WebForm2.aspx" onclick="Button1_Click" />
//this is my function to insert a line into the panel
public void createfilerow(string b, string path, bool x86check, bool x86enable, bool x64check, bool x64enable)
{
Label blank4 = new Label();
blank4.ID = "blank4";
blank4.Text = "";
Panel2.Controls.Add(blank4);
CheckBox c = new CheckBox();
c.Text = b.Replace(path, "");
c.Checked = true;
c.ID = "1a";
Panel2.Controls.Add(c);
CheckBox d = new CheckBox();
d.Checked = x86check;
d.Enabled = x86enable;
d.ID = "1b";
Panel2.Controls.Add(d);
CheckBox e = new CheckBox();
e.Checked = x64check;
e.Enabled = x64enable;
e.ID = "1c";
Panel2.Controls.Add(e);
}
//my virtual path in WebForm2.aspx
<%# PreviousPageType VirtualPath="~/WebForm1.aspx" %>
//my pageload handler
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
CheckBox tempCheckbox = (CheckBox)Page.PreviousPage.FindControl("1a");
Button1.Text = tempCheckbox.Text;
}
}
//handler which will populate the panel upon clicking
protected void Button7_Click(object sender, EventArgs e)
{
//get foldername
if (!Directory.Exists(#"myfilepath" + TextBox2.Text))
{
//folder does not exist
//do required actions
return;
}
string[] x86files = null;
string[] x64files = null;
string[] x86filespath = null;
string[] x64filespath = null;
ArrayList common = new ArrayList();
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x86"))
x86files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x86");
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x64"))
x64files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x64");
//some codes to convert x64files and x86files to string[]
//The header for Panel, 4 column
Label FL = new Label();
FL.ID = "flavourid";
FL.Text = "Flavour";
Panel2.Controls.Add(FL);
Label filetext = new Label();
filetext.ID = "filenamelabel";
filetext.Text = "File(s)";
Panel2.Controls.Add(filetext);
Label label86 = new Label();
label86.ID = "label86";
label86.Text = "x86";
Panel2.Controls.Add(label86);
Label label64 = new Label();
label64.ID = "label64";
label64.Text = "x64";
Panel2.Controls.Add(label64);
//a for loop determine number of times codes have to be run
for (int a = 0; a < num; a++)
{
ArrayList location = new ArrayList();
if (//this iteration had to be run)
{
string path = null;
switch (//id of this iteration)
{
case id:
path = some network address
}
//check the current version of iternation
string version = //version type;
//get the platform of the version
string platform = //platform
if (curent version = certain type)
{
//do what is required.
//build a list
}
else
{
//normal routine
//do what is required
//build a list
}
//populating the panel with data from list
createflavourheader(a);
//create dynamic checkboxes according to the list
foreach(string s in list)
//createrow parameter is by version type and platform
createfilerow(readin, path, true, true, false, false);
}
}
}
form1.Controls.Add(Panel2);
}
Sorry can't show you the full code as it is long and I believe it should be confidential even though i wrote them all
Yes you can access, Below is an example
// On Page1.aspx I have a button for postback
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
PostBackUrl="~/Page2.aspx" />
// Page1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox t = new TextBox(); // created a TextBox
t.ID = "myTextBox"; // assigned an ID
form1.Controls.Add(t); // Add to form
}
Now on the second page I will get the value of TextBox as
// Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
// OR
string myTextBoxValue = Request.Form["myTextBox"];
}
Updated Answer:
Panel myPanel = new Panel();
myPanel.ID = "myPanel";
TextBox t = new TextBox();
t.ID = "myTextBox";
myPanel.Controls.Add(t);
TextBox t1 = new TextBox();
t1.ID = "myTextBox1";
myPanel.Controls.Add(t1);
// Add all your child controls to your panel and at the end add your panel to your form
form1.Controls.Add(myPanel);
// on the processing page you can get the values as
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
string myTextBoxValue = Request.Form["myTextBox1"];
}
I also tried using this function Response.Write("--" +
Request["TextBox1"].ToString() + "--"); And although this statement do
printout the text in the textfield on TextBox1, it only return me the
string value of textbox1. I am unable to cast it to a textbox control
in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
Hi lw,
I think you may try passing the type of control (e.g. 'tb') together with the content and creating a new object (e.g. TextBox) and assign it to templtexBox object.
My 20 cents.
Andy
I build a class that stores values from an XML file. I am loading that data into a ListBox like this:
private void LoadBookXML(string bookXML, ListBox theBookListBox)
{
XDocument loadedData = XDocument.Load(bookXML);
var data = from query in loadedData.Descendants("book")
select new Books
{
Title = (string)query.Attribute("title").Value.ToUpper(),
Theme = (string)query.Attribute("theme").Value,
Abbreviation = (string)query.Attribute("abbr").Value,
Chapters = (string)query.Attribute("chapters").Value,
Writer = (string)query.Attribute("writer").Value,
Place = (string)query.Attribute("place").Value,
Completed = (string)query.Attribute("completed").Value,
Time = (string)query.Attribute("time").Value,
Summary = (string)query.Attribute("summary").Value,
Link = (string)query.Attribute("link").Value,
Number = (string)query.Attribute("number").Value,
WriterAndPlace = "Written by " + (string)query.Attribute("writer").Value + " in " + (string)query.Attribute("place").Value,
};
theBookListBox.ItemsSource = data;
GestureService.GetGestureListener(theBookListBox).Hold += new EventHandler<GestureEventArgs>(theBookListBox_Hold);
When I press and hold an item in the ListBox, I am calling a function that brings up context menu like this:
private void theBookListBox_Hold(object sender, GestureEventArgs e)
{
AppState state = ThisApp._appState;
if (e.OriginalSource is TextBlock)
{
if (((string)((e.OriginalSource as TextBlock).Name)) == "btBookName")
{
UpdateLayout();
_cmReader = new ContextMenu();
MenuItem item = new MenuItem();
item.IsEnabled = true;
item.IsHitTestVisible = true;
TextBlock block = new TextBlock();
block.Text = "HELP, I AM TRYING TO GET DATA FROM THE BOOKS CLASS!!!";
block.TextDecorations = TextDecorations.Underline;
item.Header = block;
MenuItem item5 = new MenuItem
{
Header = "book info"
};
item5.Click += new RoutedEventHandler(bookInfo_Click);
_cmReader.Items.Add(item);
_cmReader.Items.Add(item5);
OpenContextMenu();
}
}
}
So my question is how can I access the data from the Books class that is stored into each of the ListBoxItems? I am using C#.
is that what you mean?
Books book = theBookListBox.SelectedItem as Books;
//All
foreach(Books book in theBookListBox.Items)
{
}
I think your class is inside of the form.
So its better do this...
private void LoadBookXML()
{
string bookXmL = "";
listBox theBookListBox = new ListBox();
Your other code here..
}
then.....
private void theBookListBox_Hold(object sender, GestureEventArgs e)
{
AppState state = ThisApp._appState;
if (e.OriginalSource is TextBlock)
{
if (((string)((e.OriginalSource as TextBlock).Name)) == "btBookName")
{
LoadBookXML();
Your other code here...
}
}
}