Can't add items from listbox to list - asp.net

I am trying to add all items from a listbox to list(.cs page).I added items to listbox using javascript.Now LstScan.Items.Count return zero always.I can't add items to listbox.Listbox shows values.but problem happens in my .cs file.
here is my code;
Html and javascript Code is:
<script type="text/javascript">
function displayKeyCode_demo(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code == 13) {
var textbox = document.getElementById("<%=TextBox1.ClientID%>")
var listbox = document.getElementById("<%=LstScan.ClientID%>")
var newOption = document.createElement("Option");
newOption.value = textbox.value;
newOption.innerHTML = textbox.value;
listbox.add(newOption);
}
}
</script>
<div>
<table cellspacing="3px" style="margin: 10px auto 3px 85px;">
<tr>
<td width="150px">
<asp:TextBox ID="TextBox1" runat="server" onkeypress="displayKeyCode_demo(event)"></asp:TextBox>
</td>
<td width="200px">
<asp:ListBox ID="LstScan" runat="server" Height="200px" Width="150px" AppendDataBoundItems="True" AutoPostBack="True" >
</asp:ListBox>
</td>
</tr>
</table>
</div>
here is my code behind code:
List<int> LstSOnum = new List<int>();
foreach (ListItem item in LstScan.Items) {
LstSOnum.Add(int.Parse(item.Value));
}

You can try with Text
LstSOnum.Add(int.Parse(item.Text));

Related

Images not enlarging on click in asp.net

In my page I have a large image and set of small unit images. the large image will be loaded on page load. but when i click on small images it will get enlarge and get displayed in place of large image. the small images are displaying on page . but it has no effect on clicking them
here is my code
<div class="invDetailImage">
<img id="imgenlarge" src="" runat="server" alt="" align="middle" style="max-height:380px; max-width:579px; vertical-align:middle;"/>
<asp:Label runat="server" ID="lblerr" Visible="false" style="max-height:380px; max-width:579px; vertical-align:middle;font-size:large;"></asp:Label>
</div>
<!-- SMALL IMAGES -->
<div class="invDetailPhotoBox" runat="server" id="photobox">
<asp:Label runat="server" ID="lblphotos" Text="Select a photo below to view in the window above:"></asp:Label><br />
<asp:Repeater runat="server" ID="rptrinventoryphotos" onitemdatabound="rptrinventoryphotos_ItemDataBound">
<ItemTemplate>
<img id="imgInventory" src="" runat="server" alt='<%#Eval("ImagePath")%>' style="display:none;" />
<div onclick="large('<%#Eval("ImagePath")%>')" style="float:left;clear:none; margin-left:-12px;">
<asp:Image ID="Image1" Visible="true" runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<script type="text/javascript"> function large(src) {
var str=src; document.getElementById("ctl00_ContentPlaceHolder1_imgenlarge").src = (str);
}
function loading(img) { img.src = "images/loading.gif"; }
</script>
protected void rptrinventoryphotos_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
HtmlImage img1 =(HtmlImage) e.Item.FindControl("imgInventory");
Image img = (Image)e.Item.FindControl("Image1");
img.ImageUrl = "http://localhost:22525/DWLive/ImageResizeHandler.ashx?imgPath=" + img1.Alt + "&width=75&height=56";
img.Style.Add("margin-left", "-12px");
img.Style.Add("background-image", "url('images/loading9.gif')");
img.Style.Add("background-repeat", "no-repeat");
img.Style.Add("background-position", "center left");
//img.Attributes.Add("onclick", "large('" + img1.Alt + "')");
string[] a = img1.Alt.Split((#"/").ToCharArray());
}
can anyone help please? thanks.
The problem was in JavaScript. I changed it to:
<script type="text/javascript">
function large(link) {
var str = link;
}
document.getElementById("ctl00_ContentPlaceHolder1_imgenlarge").src = (str);

Tabpanel Set visible false not working in ASP web page server side

<AjaxToolkit:tabpanel runat="server" id="nourl" headertext=" " width="90%" height="100px" visible="false" >
<headertemplate>
New
</headertemplate>
<contenttemplate >
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="center" valign="middle">
</td>
</tr>
</table>
</contenttemplate>
</AjaxToolkit:TabPanel>
</ajaxtoolkit:tabcontainer>
This is the aspx file code
In server side i set visible true this tab panel and then i set visible false in another button event it not hide the tab panel.
How to solve this problem
try
{
DataTable dtFeedurls = getDatatable();
if (dtFeedurls.Rows.Count > 0)
{
foreach (DataRow dr in dtFeedurls.Rows)
{
AjaxControlToolkit.TabPanel tb = new AjaxControlToolkit.TabPanel();
tb.ID = ("Tab" + dr["COLUMN_1"].ToString());
tb.HeaderText = dr["COLUMN_2"].ToString();
tc.Tabs.Add(tb);
}
nourl.Visible = false;
}
else
{
nourl.Visible = true;
}
tc.ActiveTabIndex = 0;
}
catch (Exception ex)
{
throw ex;
}
This the server side code

ASP.NET group data by month

I wish to group some data by month (stored in an SQL Database), with collapsible DIVs, no doubt with jQuery. I don't particularly want to use to GridView, as I'd like to stay away from tables for simplicity when writing the jQuery.
What is the best method to do this in ASP.NET, which control would I use?
Please see the following example, for an idea of what I am trying to describe:
I've created a project which displays data by month using nested repeaters, it's uploaded on Google Docs (just click File->Save to download the .zip).
Here's a brief overview of how it works:
Assuming you have a simple Orders table in the db with the following columns
OrderId
Product
Quantity
DateOfSale
Process
Execute a stored procedure to get the months for a given year (I used EntityFramework functions, you could change this to ADO.NET,LINQ etc)
Bind the returned months to a label in the master repeater(These will be your headings)
Handle the OnItemDataBound event of the master repeater, this event runs every time an item is bound to the repeater.
Inside OnItemDataBound execute a stored procedure to get all the records for the specific month and year and simply bind the returned data to the child repeater
Add little jQuery to show and hide divs and you're set.
Code
Stored procedures:
CREATE PROCEDURE dbo.GetMonthsByYear
#Year INT
AS
BEGIN
SELECT DISTINCT DATENAME(Month,DateOfSale) AS [Month] FROM Orders
WHERE Year(DateOfSale) = #Year
END
CREATE PROCEDURE dbo.GetOrdersByMonth
#Month NVARCHAR(15),
#Year INT
AS
BEGIN
SELECT * FROM Orders
WHERE (Year(DateOfSale) = #Year) AND DATENAME(MONTH,DateOfSale) = #Month
END
ASPX:
<head runat="server">
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
var showHide;
$(document).ready(function () {
showHide = function (control) {
var parent = $(control).next();
var display = parent.css('display');
if (display == "none") { parent.fadeIn('slow'); }
else { parent.fadeOut('slow'); }
};
});
</script>
<style type="text/css">
.detail
{
height:300px;
display:none;
width: 100%;
border: 1px solid black;
}
.header
{
vertical-align: top;
padding: 3px;
height: 30px;
background: black;
color: White;
font-weight: bold;
}
</style>
<title>Nested Repeater</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Select year: <asp:TextBox ID="txtYear" runat="server" /><br />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Search" /><br />
<asp:Repeater ID="masterRepeater" runat="server" OnItemDataBound="ItemDataBound">
<ItemTemplate>
<div id='<%# Container.DataItem %>' class="header" onclick="showHide(this);">
<asp:Label ID="lblMonth" runat="server" Text='<%# Container.DataItem %>' />
</div>
<div class="detail">
<asp:Repeater ID="detailRepeater" runat="server">
<HeaderTemplate>
<span style="text-decoration: underline">Product</span><br />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Product") %>' />
<asp:Label ID="lblQuantity" runat="server" Text='<%# Bind("Quantity") %>' />
<asp:Label ID="lblDateOfSale" runat="server" Text='<%# Bind("DateOfSale") %>' /><br />
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
Code behind:
protected void Search(object sender, EventArgs e)
{
int year = 0;
if (Int32.TryParse(txtYear.Text, out year))
{
orderEntities orders = new orderEntities();
List<string> months = orders.GetMonthByYear(year).ToList();
masterRepeater.DataSource = months;
masterRepeater.DataBind();
}
}
protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int year = 0;
if (Int32.TryParse(txtYear.Text, out year))
{
Label lblMonth = e.Item.FindControl("lblMonth") as Label;
if (lblMonth != null)
{
string month = lblMonth.Text;
Repeater detailRepeater = e.Item.FindControl("detailRepeater") as Repeater;
if (detailRepeater != null)
{
orderEntities orders = new orderEntities();
var ordersByMonth = orders.GetOrdersByMonth(month, year).ToList();
detailRepeater.DataSource = ordersByMonth;
detailRepeater.DataBind();
}
}
}
}
}
Result:

close Jquery Modal popup Datalist button click

i am running into a problem that i have a jquery modal popup in my usercontrol that i show on a click of a button and user selects something from datalist and then i returned some value on the parent user control in a hidden field all is fine till here but after the click on the select button i want the jquery modal to be closed also
here is some code of the div which i show in modal diaog
<asp:UpdatePanel ID="upDatagrabber" runat="server">
<ContentTemplate>
<table>
<tr>
<td>Select Category</td><td><asp:DropDownList ID="ddlTemplateCatagory"
runat="server" AutoPostBack="True"></asp:DropDownList></td>
</tr>
<tr>
<td colspan="2">
<table cellspacing="0" cellpadding="0" border="0" style="float:left;padding:5px;margin:5px;width:200px;display:block;">
<tbody>
<tr>
<asp:DataList ID="dlTemplates" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" onitemcommand="dlTemplates_ItemCommand">
<ItemTemplate>
<td style="border-right: gainsboro 1px solid; border-top: gainsboro 1px solid;
border-left: gainsboro 1px solid; border-bottom: gainsboro 1px solid;padding:5px;">
<table><tr><td>
<%# Eval("NewsletterName").ToString()%>
</td></tr>
<tr><td><asp:Button ID="btnSelectNL_Template" Text="Select" runat="server" CssClass="button" CommandArgument='<%# Eval("NewsletterId").ToString()%>' CommandName="Select"/></td></tr>
</table>
</td>
</ItemTemplate>
</asp:DataList>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</ContentTemplate>
and in the ItemCommandEvent I tried following
protected void dlTemplates_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int SelectedNewsletterId = int.Parse(e.CommandArgument.ToString());
if (NewsletterSelectedHandler!= null)
{
e.Item.Attributes.Add("onclick","jQuery('#mydialog').dialog('close');");
NewsletterSelectedHandler(SelectedNewsletterId);
}
}
}
EDIT
i shown the popup using this in my code behind
ScriptManager.RegisterClientScriptBlock(this.Page, Page.GetType(), "change", "jQuery('#mydialog').dialog('open');closedialog = 1;jQuery('#mydialog').parent().appendTo(jQuery('form:aspnetForm'));", true);
popup shown successfully but i could not close it on the button click of datalist child button i tried code provided by tugburk i checked the error console also there is no error
code for close is as followd :
<script type="text/javascript">
$(document).ready(function(){
$('#ctl00_ContentPlaceHolder1_NewsletterWizard1_TemplatePicker1_dlTemplates_ctl00_btnSelectNL_Template').click(function(){
$('#mydialog').dialog('close');
});
});
</script>
Any help would be appreciable
Many thanks in the Advance
use the following code;
$(document).ready(function(){
$('#<%= btnSelectNL_Template.ClientID %>').click(function(){
$('#id_of_your_dialog_element').dialog('close');
});
});
EDIT :
you are hardcoding your button id there;
ctl00_ContentPlaceHolder1_NewsletterWizard1_TemplatePicker1_dlTemplates_ctl00_b‌​tnSelectNL_Template
DataList will produce multiple buttons if you have multiple records. add a class name to that button, and try to write a code against it
$('.MyButtonClass').click(function(){
$('#mydialog').dialog('close');
});

Gridview column color doesnt fill entire box

I have a gridview with certain boxes that are highlighted in green. These boxes should fill the entire box, but I can't seem to trash this 1px border around the edges. I'm using IE7, but FF does it too.
Rendered html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title><link href="Style/StyleSheet.css" rel="stylesheet" type="text/css" /><link href="App_Themes/Contoso/Style.css" type="text/css" rel="stylesheet" /></head>
<body>
<form name="form1" method="post" action="GridViewColoring.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODIyMTgxMzQxZBgBBQh0ZXN0R3JpZA88KwAMAQgCAWR6Qz5BuXEoalr4HjsTfYqqKPrdwd2ICIXpeNacwdi46w==" />
</div>
<div>
<div>
<table class="cssTable" cellspacing="0" rules="all" border="1" id="testGrid" style="border-collapse:collapse;">
<tr>
<th scope="col">Description</th><th scope="col">Serial#</th>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl02_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl02_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;height:100%;width:100%;">0</span>
</td>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl03_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl03_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;background-color:#CCFFCC;height:100%;width:100%;">1000</span>
</td>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl04_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl04_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;background-color:#CCFFCC;height:100%;width:100%;">2000</span>
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
test case
CSS
body {
}
.NoMargin
{
margin:0 0 0 0;
}
.NoPadding
{
padding:0 0 0 0;
}
.BgColor
{
background-color:Aqua;
}
.MaxHeightAndWidth
{
height:100%;
width:100%;
}
.NoBorder
{
border:0px;
}
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewColoring.aspx.cs" Inherits="WebApplication1.GridViewColoring" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView id="testGrid" runat="server" CssClass="cssTable"
AutoGenerateColumns="False"
OnRowDataBound="SetStatusColors" >
<Columns>
<asp:TemplateField HeaderText="Description" SortExpression="description" ItemStyle-CssClass="NoMargin NoPadding">
<ItemTemplate>
<asp:Label ID="descriptionLbl" runat="server" Text='<%# Bind("description") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Serial#" SortExpression="serial">
<ItemTemplate>
<asp:Label ID="serialNumberLbl" runat="server" Text='<%# Bind("serial") %>' CssClass="NoMargin NoPadding MaxHeightAndWidth NoBorder" Height="100%" Width="100%"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C# backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class GridViewColoring : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
testGrid.DataSource = MakeTable();
testGrid.DataBind();
}
protected void SetStatusColors(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < testGrid.Rows.Count; i++)
{
string serialNumber = ((Label)testGrid.Rows[i].FindControl("serialNumberLbl")).Text;
if (serialNumber != "0")
{
//GREEN HIGHLIGHTS
((Label)testGrid.Rows[i].FindControl("serialNumberLbl")).BackColor = System.Drawing.Color.FromArgb(204, 255, 204);
}
testGrid.Rows[i].BackColor = System.Drawing.Color.Yellow;
}
}
//mock db
private DataSet MakeTable()
{
var table = new DataTable("ParentTable");
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "serial";
column.ReadOnly = true;
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);
//// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "description";
column.AutoIncrement = false;
column.Caption = "Description";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Instantiate the DataSet variable.
var dataSet = new DataSet();
// Add the new DataTable to the DataSet.
dataSet.Tables.Add(table);
// Create three new DataRow objects and add
// them to the DataTable
for (int i = 0; i <= 2; i++)
{
row = table.NewRow();
row["serial"] = i * 1000;
row["description"] = "Some desc " + DateTime.Now;
table.Rows.Add(row);
}
return dataSet;
}
}
}
Update
Changed the Serial# template's itemstyle and it fixed the problem. I have no idea why, but thanks to your tips, I was able to reduce the problem down enough to try it:
<ItemStyle Font-Size="Smaller" CssClass="NoMargin NoPadding" />
Try setting border-collapse: collapse; on the cssTable css class.
Okay I was able to get it working. I took the css classes off of the first template item and created the following css.
table.cssTable
{
border-collapse: collapse;
}
table.cssTable tr td
{
background: Yellow;
font-size:Smaller;
margin: 0;
padding: 0;
}
By the way, you should be able to get rid of the ItemStyle with font-size as well with this CSS.
I've created a fiddle but can't really see the problem I'm afraid - http://jsfiddle.net/5rBYb/1/
You might want to try adding this to your CSS though, which will set the borders to a single pixel (which I suspect is what's causing your problem).
table, th, td { border: 1px solid #000; }
Just change it to border: 0 if you want to hide borders.

Resources