Checkboxes checked value ever false in repeater - c#

I am newbie with ASP .NET. I am using a repeater with parent checkboxes (User Type) and inside alse i am using other repeater control for to show User Type Divisions.
Because Checkbox Microsoft ASP control don´t have a value I am using html input type checkboxes because i need perform any actions with javascript and jquery.
My code is the next:
ASPX CODE
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Admin/Admin.Master"
CodeBehind="Editar.aspx.cs" Inherits="ELearning.Admin.Cursos.Editar" ValidateRequest="true" %>
<%# Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<title>Editar Curso</title>
<script type="text/javascript" src="../../js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="../../js/funcionesGenerales.js"></script>
<script type="text/javascript" src="../../ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../ckfinder/ckfinder.js"></script>
<script type="text/javascript">
window.onload = function () {
//editor = CKEDITOR.replace('editor');
CKFinder.setupCKEditor(null, '../../ckfinder/');
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true" />
<h2 class="principalTitle">
<asp:Label runat="server" ID="lblID"></asp:Label>
</h2>
<div>
<h2>
Titulo:
<asp:TextBox runat="server" Width="500px" ID="txtTitulo"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfTitulo" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="txtTitulo"></asp:RequiredFieldValidator>
<%--<asp:RequiredFieldValidator ID="rfvTitulo" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="txtTitulo" />--%>
<asp:RegularExpressionValidator ID="maxLenTxtTitulo" ControlToValidate="txtTitulo"
CssClass="Validator" ValidationExpression="(\s|.){0,256}$" Text="El titulo es demasiado largo. La longitud máxima es de 256."
runat="server" />
</h2>
</div>
<div>
<h2>
Objetivos:
<asp:RequiredFieldValidator ID="rfvObjetivos" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heObjetivos" />
</h2>
<p>
<CKEditor:CKEditorControl ID="heObjetivos" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
</div>
<div>
<h2>
Destinatarios:
<asp:RequiredFieldValidator ID="rfvDestinatarios" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heDestinatarios" /></h2>
<p>
<CKEditor:CKEditorControl ID="heDestinatarios" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
</div>
<h2>
Modalidad del curso
<asp:RequiredFieldValidator ID="rfvModalidad" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heModalidad" />
</h2>
<p>
<CKEditor:CKEditorControl ID="heModalidad" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
<h2>
Tipos de usuario que lo pueden ver</h2>
<ul>
<asp:Repeater ID="rptTipoUsuarios" runat="server">
<ItemTemplate>
<li class="listItems">
<input type="checkbox" id="chkTipoUsuario" class='<%# "chkTipoUsuario-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>'
value='<%# DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>' runat="server"
onclick="seleccionarTodos($(this).is(':checked'), $(this).attr('id'))" />
<span id="nombreTipoUsuario" class='<%# "nombreTipoUsuario-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>'>
<%# DataBinder.Eval(Container.DataItem, "Nombre") %>
</span>
<ul>
<asp:Repeater ID="rptDivisiones" runat="server">
<ItemTemplate>
<li class="listSubItems"><span class='<%# "chkDivision-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId")%>'>
<input type='checkbox' id="chkDivision" class='<%# "chkDivision-class-" + DataBinder.Eval(Container.DataItem, "DivisionId")%>'
value='<%# DataBinder.Eval(Container.DataItem, "DivisionId") %>' runat="server"
onclick="sumarCheckeo($(this).attr('class'))" />
<%# DataBinder.Eval(Container.DataItem, "Nombre") %>
</span></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<div>
<h2>
<span style="display: none">
<asp:TextBox ID="contadorCheckeos" ClientIDMode="Static" Text="0" runat="server"></asp:TextBox>
<asp:CheckBox ID="chkAuxOtros" ClientIDMode="static" runat="server" />
</span>
<asp:RegularExpressionValidator CssClass="Validator" ID="revChkQuantity" ControlToValidate="contadorCheckeos"
runat="server" Text="Debe seleccionar al menos 1 division" ValidationExpression="[1-9]*\.?[0-9]*[1-9]">
</asp:RegularExpressionValidator>
</h2>
</div>
<div>
<asp:Button runat="server" ID="btnSubmit" Text="Actualizar"></asp:Button>
</div>
</asp:Content>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ELearning.Admin.Cursos
{
public partial class Editar : System.Web.UI.Page
{
private ELearningContextDataContext db;
private int cursoId;
private List<DataObject.CursoDivision> cursoDivisiones;
protected void Page_Load(object sender, EventArgs e)
{
DeclararHandlers();
InicializarConexionDB();
((Admin)this.Master).PermitirORedireccionarAdmin();
Int32.TryParse(Request.QueryString["id"], out cursoId);
if(!((from p in db.Cursos where p.CursoId == cursoId select p).ToArray().Length > 0))
Response.Redirect("Default.aspx");
if (!Page.IsPostBack)
{
CargarColecciones();
CargarDatos();
}
}
protected void CargarColecciones()
{
CargarTiposDeUsuario();
CargarDivisiones();
}
protected void CargarTiposDeUsuario()
{
var tipoUsuarios = DataObject.TipoUsuario.ObtenerTodos(db, false);
rptTipoUsuarios.DataSource = tipoUsuarios;
rptTipoUsuarios.DataBind();
}
protected void CargarDivisiones()
{
var divisiones = DataObject.Division.ObtenerTodos(db);
}
protected void InicializarConexionDB()
{
db = new ELearningContextDataContext();
}
protected void DeclararHandlers()
{
btnSubmit.Click += new EventHandler(btnSubmit_Click);
rptTipoUsuarios.ItemDataBound += new RepeaterItemEventHandler(rptTipoUsuarios_ItemDataBound);
}
protected void rptTipoUsuarios_ItemCreated(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = (RepeaterItem)e.Item;
if (ri.ItemType == ListItemType.Item ||
ri.ItemType == ListItemType.AlternatingItem)
{
Repeater rptDivisiones = (Repeater)ri.FindControl("rptDivisiones");
rptDivisiones.ItemCreated += new RepeaterItemEventHandler(rptDivisiones_ItemCreated);
}
}
protected void rptTipoUsuarios_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)e.Item.FindControl("chkTipoUsuario");
chk.ID = "chkTipoUsuario-" + e.Item.ItemIndex;
if (string.Compare(((ELearning.TipoUsuario)(e.Item.DataItem)).Nombre.ToLower(), "otros") == 0)
{
//Ver si se checkeo
//Se puede crear un enum para los tipo de usuario y las divisiones
Int32.TryParse(Context.Request.QueryString["id"], out cursoId);
var query = from p in db.CursoDivisiones where p.CursoId == cursoId && p.DivisionId == 8 select p;
if (query.ToArray().Length > 0)
{
chk.Checked = true;
chkAuxOtros.Checked = true;
}
}
//((System.Web.UI.HtmlControls.HtmlInputCheckBox)chk).Checked = false;
Repeater ChildRepeater = (Repeater)e.Item.FindControl("rptDivisiones");
LlenarRepeaterInterno(ChildRepeater, ((ELearning.TipoUsuario)e.Item.DataItem).TipoUsuarioId);
}
}
protected void LlenarRepeaterInterno(Repeater childRepeater, int tipoUsuarioId)
{
/*SELECT * FROM Divisiones INNER JOIN TipoUsuarios as tu on tu.TipoUsuarioId = Divisiones.TipoUsuarioId WHERE Divisiones.TipoUsuarioId = 1 AND tu.Nombre != 'Otros'*/
var query = (from p in db.Divisiones join q in db.TipoUsuarios on p.TipoUsuarioId equals q.TipoUsuarioId where p.TipoUsuarioId == tipoUsuarioId && string.Compare(q.Nombre.ToLower(), "Otros".ToLower()) != 0 select p).Distinct();
childRepeater.DataSource = query;
childRepeater.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//CODE FOR SUBMIT
}
catch (Exception ex)
{
//Manejar excepcion
}
}
protected List<DataObject.CursoDivision> CrearCursoDivision()
{
try
{
List<DataObject.CursoDivision> divisiones = new List<DataObject.CursoDivision>();
int divisionId;
int tipoUsuarioId;
foreach (RepeaterItem item in rptTipoUsuarios.Items)
{
var checkboxTipoUsuario = (System.Web.UI.HtmlControls.HtmlInputCheckBox)item.FindControl("chkTipoUsuario");
Int32.TryParse(checkboxTipoUsuario.Value, out tipoUsuarioId);
if (!DataObject.TipoUsuario.esOtros(db, tipoUsuarioId))
{
Repeater rptDivisiones = (Repeater)item.FindControl("rptDivisiones");
if (rptDivisiones != null)
{
foreach (RepeaterItem itemDivision in rptDivisiones.Items)
{
var checkbox = (System.Web.UI.HtmlControls.HtmlInputCheckBox)itemDivision.FindControl("chkDivision");
if (checkbox.Checked)
{
Int32.TryParse(checkbox.Value, out divisionId);
divisiones.Add(new DataObject.CursoDivision(0, divisionId));
}
}
}
}
else
{
if (chkAuxOtros.Checked)
{
var query = db.Divisiones.Single(q => q.TipoUsuarioId == tipoUsuarioId);
divisiones.Add(new DataObject.CursoDivision(0, query.DivisionId));
}
}
}
return divisiones;
}
catch (Exception ex)
{
throw ex;
}
}
protected void CargarDatos()
{
try
{
Int32.TryParse(Context.Request.QueryString["id"], out cursoId);
//CKFinder.FileBrowser _fileBrowser = new CKFinder.FileBrowser();
//_fileBrowser.BasePath = "/ckfinder/";
//_fileBrowser.SetupCKEditor(null);
if (!Page.IsPostBack && cursoId != 0)
{
var curso = db.Cursos.Single(p => p.CursoId == cursoId);
lblID.Text = string.Format("Editando Curso ID #{0}", cursoId.ToString());
txtTitulo.Text = curso.Titulo;
heObjetivos.Text = curso.Descripcion;
heModalidad.Text = curso.Modalidad;
heDestinatarios.Text = curso.Destinatario;
var query = from q in db.CursoDivisiones
where q.CursoId == cursoId
select q.DivisionId;
string divisionesSeleccionadas = string.Join(",", query.ToArray());
Page.ClientScript.RegisterStartupScript(GetType(), "JSScript", string.Format("tildar('{0}')", divisionesSeleccionadas), true);
}
else
{
if (cursoId == 0)
Response.Redirect("Default.aspx");
}
}
catch (Exception ex)
{
//REdirige hacia pagina de error
}
}
}
}
My problem is that the parent checkbox ever is in false state in Checked property.
Also This page don`t perform correctly the validation actions. When i write in Firebug console validation asp function also return true state.
Which could be the problems?
Thanks in advance

Finally I use a simple html input tag for checkbox adding the onserverclick attribute.
Therefore not is necessary the autopostback.
Thanks and excuse me.
Accept suggestions in comments.

Related

C# DropDownList SelectedValue is set but not saving?

I feel like I'm missing something really obvious. :)
C# ASPX page, testing in most recent version of Chrome.
Here's the relevant code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="JobSearch.aspx.cs" Inherits="GCWebForms.Jobs.JobSearch" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="Head" runat="server">
<style>
a img{border: none;}
ol li{list-style: decimal outside;}
div#container{width: 780px;margin: 0 auto;padding: 1em 0;}
div.side-by-side{width: 100%;margin-bottom: 1em;}
div.side-by-side > div{float: left;width: 50%;}
div.side-by-side > div > em{margin-bottom: 10px;display: block;}
.clearfix:after{content: "\0020";display: block;height: 0;clear: both;overflow: hidden;visibility: hidden;}
</style>
<link rel="stylesheet" href="../Content/chosen.css" />
</asp:Content>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="body-content">
<div id="searchform" class="simplelayoutform">
<div>
<div>
<asp:label id="lblCustomerSearch" runat="server" Text="Jobs for Customer:" AssociatedControlID="cboCustomerID" />
<asp:DropDownList ID="cboCustomerID" runat="server" class="chzn-select"
DataSourceID="DataSourceCustomer" DataTextField="CustomerName" DataValueField="CustomerID">
</asp:DropDownList>
<gcctl:MyCheckBox ID="chkCustomersShowInactive" Text="Show Inactive?" Checked="false" AutoPostBack="true" runat="server" />
</div>
</div>
[[cut - search results go here]]
</div>
<asp:SqlDataSource ID="DataSourceCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnString %>"
SelectCommand="SELECT NULL AS [CustomerID]
, NULL AS [CustomerName]
UNION SELECT [CustomerID]
,[CustomerName]
FROM [dbo].[Customers]
WHERE ((#ShowInactive = 0 AND IsActive = 1) OR (#ShowInactive = 1))
ORDER BY CustomerName">
<SelectParameters>
<asp:ControlParameter Name="ShowInactive" Type="Boolean" ControlID="chkCustomersShowInactive" PropertyName="Checked" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="JQScripts" runat="server">
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("PageForm").target != "_blank") return;
opener.document.getElementById("PageForm").target = "";
opener.document.getElementById("PageForm").action = opener.location.href;
}
</script>
<script src="../Scripts/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); </script>
</asp:Content>
JobSearch.aspx.cs (relevant parts):
namespace GCWebForms.Jobs
{
public partial class JobSearch : System.Web.UI.Page
{
int? iCustomerID;
int? iStaffID;
bool bolIsPostBack = false;
//--------
protected void SetIDs()
{
this.iCustomerID = null;
this.iStaffID = null;
if (Request.QueryString["customerid"] != null) //new customer
{
try
{
this.iCustomerID = Convert.ToInt32(Request.QueryString["customerid"]);
}
catch { }
}
if (Request.QueryString["staffid"] != null) //new customer
{
try
{
this.iStaffID = Convert.ToInt32(Request.QueryString["staffid"]);
}
catch { }
}
if (iCustomerID != null)
{
this.cboCustomerID.SelectedValue = this.iCustomerID.ToString();
}
if (iStaffID != null)
{
this.cboStaffID.SelectedValue = this.iStaffID.ToString();
}
}
//--------
protected void DoSearch()
{
//gvJobsDataSource.SelectParameters["CustomerSearch"].DefaultValue = cboCustomerID.SelectedValue.ToString();
//gvJobsDataSource.SelectParameters["StaffSearch"].DefaultValue = cboStaffID.SelectedValue.ToString();
//gvJobsDataSource.SelectParameters["ShowClosed"].DefaultValue = chkShowClosed.Checked.ToString();
if(string.IsNullOrEmpty(this.cboCustomerID.SelectedValue.ToString()) && string.IsNullOrEmpty(this.cboStaffID.SelectedValue.ToString()))
{
SearchPrompt.Visible = this.bolIsPostBack;
gvJobs.DataSourceID = "gvJobsDataSourceInit";
} else
{
SearchPrompt.Visible = false;
gvJobs.DataSourceID = "gvJobsDataSource";
}
gvJobs.DataBind();
}
//--------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetIDs();
DoSearch();
}
this.bolIsPostBack = true;
}
//--------
protected void btnSearch_Click(object sender, EventArgs e)
{
DoSearch();
}
Issue: When I run, for example, http://server/Jobs/JobSearch?customerid=22, it's supposed to load customerID 22 into a dropdownlist of customers. And then it's supposed to do a search on that customer. It does the first thing, but not the second.
That is, I can SEE that the customer with the ID 22 has been automatically selected in the dropdownlist. But when I step through the PageLoad routine, it runs SetIDs(), where it does set this.cboCustomerID.SelectedValue = '22', but then when it runs DoSearch() and I put a watch on this.cboCustomerID.SelectedValue.ToString(), it returns '', and so no search is run.
Why is this.cboCustomerID.SelectedValue.ToString() returning '' when I just set its value to '22'?
Many thanks!

Use asp.net button onclick method instead of submitting form

I have an asp.net Button control which I want to use to insert comments in my page. When i click on button, I want it to call a method instead of submitting the form. How do i achieve this?
This is what i have tried so far -
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
//Do some stuff here
}
</script>
<head>title and other css links go here</head>
<body>
<form id="form1" runat="server" onsubmit="false">
//Some other asp.net controls go here
<asp:Button ID="Button1" runat="server" Text="Comment" OnClick="Button1_Click"/>
</form>
</body>
</html>
Is there any other way to achieve what I am doing? Suggestions are welcome.
I don't really know exactly what you are meaning.... I think you are asking for how to insert a comment into an aspx via a shout box???... Maybe?
Here is the code to insert whatever you want to type(a comment) into your form from a "method"... although it uses a lot more than just a single method.. this is the simplest way I can think of...
This is your default.aspx (notice no master page here)
<!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 id="Head1" runat="server">
<title>AJAX Example for comment</title>
<link href="Main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id="page">
<div id="main">
<div id="shoutbox">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>Here's what everyone is saying:</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblShoutBox" runat="server"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="5000">
</asp:Timer>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddShout"
EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p class="label">Name:</p>
<p class="entry">
<asp:TextBox ID="txtUserName" runat="server"
MaxLength="15" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ErrorMessage="Name is required."
ControlToValidate="txtUserName" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<p class="label">Shout:</p>
<p class="entry">
<asp:TextBox ID="txtShout" runat="server"
MaxLength="255" Width="220px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server" ErrorMessage="Shout is required."
ControlToValidate="txtShout" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<asp:Button ID="btnAddShout" runat="server" Text="Add Shout"
onclick="btnAddShout_Click" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
DynamicLayout="False">
<ProgressTemplate>
<img src="Images/spinner.gif" alt="Please Wait" />
Comment...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</p>
</div>
</div>
</div>
</form>
</body>
</html>
And this is your C# Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShoutItemList shoutBox;
if (Application["ShoutBox"] == null)
{
shoutBox = new ShoutItemList();
Application.Add("ShoutBox", shoutBox);
}
else
{
shoutBox = (ShoutItemList)Application["ShoutBox"];
lblShoutBox.Text = shoutBox.Display();
}
if (ScriptManager1.IsInAsyncPostBack != true)
txtUserName.Focus();
}
protected void btnAddShout_Click(object sender, EventArgs e)
{
ShoutItem shout = new ShoutItem();
shout.UserName = txtUserName.Text;
shout.Comment = txtShout.Text;
shout.Timestamp = DateTime.Now;
Application.Lock();
ShoutItemList shoutBox = (ShoutItemList)Application["ShoutBox"];
shoutBox.Add(shout);
Application.UnLock();
lblShoutBox.Text = shoutBox.Display();
txtShout.Text = "";
txtShout.Focus();
}
}
public class ShoutItem
{
public string UserName { get; set; }
public DateTime Timestamp { get; set; }
public string Comment { get; set; }
}
public class ShoutItemList
{
private List<ShoutItem> shoutList = new List<ShoutItem>();
private void Purge()
{
DateTime purgeTime = DateTime.Now;
purgeTime = purgeTime.AddMinutes(-3);
int i = 0;
while (i < shoutList.Count)
{
if (shoutList[i].Timestamp <= purgeTime) shoutList.RemoveAt(i);
else i += 1;
}
}
public void Add(ShoutItem shout)
{
Purge();
System.Threading.Thread.Sleep(2000);
shoutList.Insert(0, shout);
}
public string Display()
{
Purge();
StringBuilder shoutBoxText = new StringBuilder();
if (shoutList.Count > 0)
{
shoutBoxText.AppendLine("<dl>");
foreach (ShoutItem shout in shoutList)
{
shoutBoxText.Append("<dt>" + shout.UserName + " (");
shoutBoxText.Append(shout.Timestamp.ToShortTimeString() + ")</dt>");
shoutBoxText.AppendLine("<dd>" + shout.Comment + "</dd>");
}
shoutBoxText.AppendLine("</dl>");
}
return shoutBoxText.ToString();
}
}
This will allow you to insert whatever comment you want. You can modify this code to your own please....
Let me know if this is the answer you seek.
Use the button's OnClientClick, like this:
<asp:Button ID="Button1" runat="server" Text="Comment" OnClientClick="return javascriptFunction();" OnClick="Button1_Click"/>
then your javascript function would look like this
function javascriptFunction() {
//do something here
return false; //if you don't want the form to POST to the server, leave this as false, otherwise true will let it continue with the POST
}

Chat Application using Asp.net giving Database errors

I am making a Chat Application in ASP.NET using AJAX,LINQ to SQL and some security features for authentication purpose.The Chat will be according to a specific group.I am getting an error after I attempt to login to the Chat page(default.aspx,in my project) ,
the error is :
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tbmsg_tbusr2". The conflict occurred in database "test", table "dbo.tbusr", column 'usrcod'.
The statement has been terminated."
Note : tbmsg is a table for storing data about messages and tbusr for storing data about users.
The Back end Code for Default.aspx is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
chatDataContext obj = new chatDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Label1.Text = "Welcome:" + Session["usrnam"].ToString();
Insert_Msg("Just Login:");
GetLoggedUser();
Get_Msg();
}
}
private void Insert_Msg(String m)
{
tbmsg k = new tbmsg { msgdsc = m, msgdat = DateTime.Now, msgfrmusrcod = Convert.ToInt32(Session["usrcod"]), msgtousrcod = null, msggrpcod = Convert.ToInt32(Request.QueryString["grpcod"]) };
obj.tbmsgs.InsertOnSubmit(k);
obj.SubmitChanges();
}
private void Get_Msg()
{
var q = from p in obj.tbmsgs
where p.msggrpcod == Convert.ToInt32(Request.QueryString["grpcod"])
select p;
StringBuilder sb = new StringBuilder();
foreach (var t in q)
{
sb.Append(t.msgdsc + ":" + t.msgdat.ToString() + ":" + t.tbusr.usrnam + "<br/>");
}
ltmsg.Text = sb.ToString();
}
private void GetLoggedUser()
{
var q = (from p in obj.tblogusrs where p.logusrusrcod == Convert.ToInt32(Session["usrcod"]) select p).SingleOrDefault();
if (q == null)
{
tblogusr x = new tblogusr { logusrusrcod = Convert.ToInt32(Session["usrcod"]), logusrgrpcod = Convert.ToInt32(Request.QueryString["grpcod"]) };
obj.tblogusrs.InsertOnSubmit(x);
obj.SubmitChanges();
}
StringBuilder sb = new StringBuilder();
var q1 = from p in obj.tblogusrs where p.logusrgrpcod == Convert.ToInt32(Request.QueryString["grpcod"]) select p;
foreach (var t in q1)
{
sb.Append(t.tbusr.usrnam + "<br/>");
}
ltuser.Text = sb.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Length > 0)
{
Insert_Msg(TextBox1.Text);
TextBox1.Text = String.Empty;
TextBox1.Focus();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
var q = (from p in obj.tblogusrs where p.logusrusrcod == Convert.ToInt32(Session["usrcod"]) select p).SingleOrDefault();
if (q != null)
{
obj.tblogusrs.DeleteOnSubmit(q);
obj.SubmitChanges();
}
Insert_Msg("Just Logout:");
FormsAuthentication.SignOut();
Response.Redirect("login.aspx");
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Get_Msg();
GetLoggedUser();
}
}
The HTML Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1
{
width: 70%;
height: 25px;
}
.auto-style2
{
height: 25px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 286px; width: 849px">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
</asp:Timer>
<table border="5" style="width: 100%; margin-right: 0px">
<tr>
<td width="30%" class="auto-style2">
<asp:Literal ID="ltuser" runat="server" />
</td>
<td class="auto-style1">
<asp:Literal ID="ltmsg" runat="server" />
</td>
</tr>
</table>
<br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send" />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Logout" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Description for tbusr table:
usrcod int primary key (auto increment)
usrnam varchar(50)
usrpwd varchar(50)
Description for tbmsg table:
msgcod int primary key (auto increment)
msgdsc varchar(100)
msgdat datetime
msgfrmusrcod int (foreign key with usrcod of tbusr)
msgtousrcod int (foreign key with usrcod of tbusr)
msggrpcod int (foreign key with grpcod of tbgrp)
Note : tbgrp is another table for storing data about groups

Getting a string in code-behind containing the selections in a multi-select listbox?

What I want to do is take all of the selected items from a milti-select listbox and put them in a comma separated string, so I can store it in a table. I've searched and found code, but for some reason the qualifier is never found to be "true". It sees every selected item as "false". Am I processing this in the wrong order?
Here's my ASP section (cut because it's a HUGE file, but this is the important stuff):
<%# Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PBR.WebForm1" MaintainScrollPositionOnPostback="true"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<link rel="stylesheet" href="Styles/ui.all.css" type="text/css" media="screen" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanelX" runat="server" UpdateMode="Conditional" Height="390px"
Width="900px" BorderStyle="Groove" BorderWidth="2px">
<ContentTemplate>
<AJAXControls:TabContainer runat="server" ID="tabContainer" Height="373" Width="900" >
<AJAXControls:TabPanel ID="secondTab" HeaderText="Tracking Page 2" runat="server">
<ContentTemplate>
<div style="border:1px solid blue;">
<asp:Panel ID="Panel2" runat="server" Height="40px" style="margin-left: 19px"
Width="860px">
<table>
<tr>
<td width="170">System/Document Change:</td>
<td width="30"><asp:ListBox id="ddlSysDocChg" runat="server" Width="90px" Rows="2" SelectionMode="Multiple"></asp:ListBox></td>
<td width="40"></td>
<td width="200">System/Document Change Completed:</td>
<td width="20"><asp:CheckBox ID="chkSysDocChg" runat="server" Text=" " AutoPostBack="true" /></td>
</tr>
</table>
</asp:Panel>
</div>
<p></p>
<div>
</div>
</ContentTemplate>
</AJAXControls:TabPanel>
</AJAXControls:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_OnClick"
runat="server" />
</div>
</asp:Content>
In my code-behind, I have this (as you can see, I've tried it 2 different ways and I believe I found both methods on this very website):
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Read the selected items from the listbox
//string SQLCode = "";
var selectedQuery = ddlSysDocChg.Items.Cast<ListItem>().Where(item => item.Selected);
string SQLCode = String.Join(",", selectedQuery).TrimEnd();
//foreach (ListItem listitem in ddlSysDocChg.Items)
// {
// if (listitem.Selected == true)
// {
// SQLCode = SQLCode + ", " + listitem;
// }
// }
}
Can anyone tell me why it always tells me there's nothing selected?
EDIT:
This is what's in my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
// Check to see which tabs should be active
LoadTabPages();
{
try
{
string strSQL = "SELECT ComboValue, ComboText FROM dbo.tblComboBoxes WHERE ComboName = 'ddlSysDocChg' ORDER BY ComboText ASC;";
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, str);
DataSet DailyRun = new DataSet();
adapter.Fill(DailyRun);
ddlSysDocChg.DataSource = DailyRun;
ddlSysDocChg.DataTextField = "ComboText";
ddlSysDocChg.DataValueField = "ComboValue";
ddlSysDocChg.DataBind();
foreach (ListItem item in ddlSysDocChg.Items)
{
item.Attributes.Add("Title", item.Text);
}
// Insert a blank row into the DropDownLists so there is no default name
ddlSysDocChg.Items.Insert(0, new ListItem("", ""));
}
catch (Exception ex)
{
// Handle the error
Console.WriteLine("Making Call to " + ex + "");
}
}
}
I think it's because your list is in an updatepanel whose postback is 'Conditional', and the button is 'outside' the updatepanel.
Try putting it 'inside' the update panel as in this tutorial:
http://msdn.microsoft.com/en-us/library/Bb399001(v=VS.100).aspx
Or alternatively, specify the button as a 'Trigger' as in the same tutorial.
Do you databind the ListBox also postbacks? Check the IsPostBack property:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack) DataBindListBox();
}

Finding controls in repeater on commandargument

I have a repeater:
<asp:Repeater ID="rpt_Items" OnItemCommand="rpt_Items_ItemCommand" runat="server">
<ItemTemplate>
<div class="item">
<div class="fr">
<asp:TextBox ID="tb_amount" runat="server">1</asp:TextBox>
<p>
<%# Eval("itemPrice") %>
</p>
<asp:LinkButton ID="lb_buy" CommandName="buy" runat="server">buy</asp:LinkButton>
</div>
<asp:HiddenField ID="hdn_ID" Value='<%# Eval("itemID") %>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
On the repeater commandargument i want to get the textbox and the hiddenfield but how do i do this?
protected void rpt_Items_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "buy")
{
//ADD ITEM TO CART
Response.Write("ADDED");
Product getProduct = db.Products.FirstOrDefault(p => p.ProductID == id);
if (getProduct != null)
{
CartProduct product = new CartProduct()
{
Name = getProduct.ProductName,
Number = amount,
CurrentPrice = getProduct.ProductPrice,
TotalPrice = amount * getProduct.ProductPrice,
};
cart.AddToCart(product);
}
}
}
Thanks a bunch!
You don't have to pass it through the Command Argument, you can use e.Item.FindControl() inside your rpt_Items_ItemCommand method, as in:
TextBox tb_amount = (TextBox)e.Item.FindControl("tb_amount");
HiddenField hdn_ID = (HiddenField)e.Item.FindControl("hdn_ID");

Categories

Resources