Archive

Archive for April, 2012

Disable Validation based on Condition

April 20, 2012 Leave a comment

Hi all,

try this example to Disable Validation based on Condition


<asp:DropDownList ID="ddlList" runat="server" OnChange="ValidateIf();">
 <asp:ListItem Value="Y" Text="Yes"></asp:ListItem>
 <asp:ListItem Value="N" Text="No"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="val" runat="server" ControlToValidate="txtName"
 ValidationGroup="Group1" Display="Dynamic"
 ErrorMessage="Please enter name">
</asp:RequiredFieldValidator>
<asp:Button ID="btn" runat="server" Text="Submit" ValidationGroup="Group1" CausesValidation="true" />

and use this javascript :


function ValidateIf() {
 var list = document.getElementById('ddlList');
 var val = document.getElementById('val');

 if (list.options[list.selectedIndex].value == "Y") {
 ValidatorEnable(val, true);
 }
 else {
 ValidatorEnable(val, false);
 }
}

Hope this helps

Good Luck.

Categories: ASP.Net, Javascript

Bind HTML DropdownList from Database

April 4, 2012 2 comments

Hi all,

try this example to Bind HTML DropdownList from Database using ADO.NET

In this example i will use Northwind database

1) Open VS2008 and create a new website and add web page

2) From Toolbox drag and drop HTML Select and HTML Button control


<head runat="server">
 <title></title>
 <script type="text/javascript">
 function getValues() {
 var opt = document.getElementById('Select1');
 var selected = "";
 var Text = "";
 var index = 0;
 for (var intLoop = 0; intLoop < opt.length; intLoop++) {
 if (opt[intLoop].selected) {
 selected += opt[intLoop].value + ',';
 Text += opt[intLoop].text + ',';
 }
 }
 alert('Selected Value '+selected+' --- selected Text '+Text);
 }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <select id="Select1" multiple="multiple">
 </select>
 <input id="Button1" type="button" value="Get Values" onclick="getValues();" />
 </div>
 </form>
</body>

and in code behind :-


private void Bind()
 {
 string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
 SqlConnection connection = new SqlConnection(constr);
 string sql1 = "select * from Categories";
 SqlDataAdapter sda1 = new SqlDataAdapter(sql1, connection);
 DataSet ds1 = new DataSet();
 sda1.Fill(ds1, "Categories");

StringBuilder str = new StringBuilder();
 str.Append("<script language=javascript>");
 int i;
 for (i = 0; i < ds1.Tables["Categories"].Rows.Count; i++)
 {
 string id = ds1.Tables["Categories"].Rows[i]["CategoryName"].ToString().Trim();
 string name = ds1.Tables["Categories"].Rows[i]["CategoryID"].ToString().Trim();
 str.Append("document.getElementById(\"Select1\").options.add(new Option(\"" + id + "\", \"" + name + "\"));");
 }
 str.Append("</script>");
 Page.ClientScript.RegisterStartupScript(this.GetType(), "clientscript", str.ToString());
 }

protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 Bind();
 }
 }

Don’t forget to use the following Namespaces


using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

3) In Web.Config file add ConnectionString


<connectionStrings>
 <add name="conn" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"
 providerName="System.Data.SqlClient" />
 </connectionStrings>

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

Send Gridview Content Through Email

April 3, 2012 3 comments

Hi all,

try this example to send Gridview content through email

In this example i will use Northwind Database to bind it to Gridview and it’s content through Email

1) Open VS2008 and create a new website and add new web page and from Toolbox drag Button and Gridview and bind it using SqlDataSouces control


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
 EnableEventValidation="false" %>

<!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>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
 DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ForeColor="#333333">
 <RowStyle BackColor="#EFF3FB" />
 <Columns>
 <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
 ReadOnly="True" SortExpression="ProductID" />
 <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
 <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
 <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
 <asp:TemplateField HeaderText="Discontinued" SortExpression="Discontinued">
 <ItemTemplate>
 <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("Discontinued") %>'
 Enabled="false" />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
 <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
 <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 <EditRowStyle BackColor="#2461BF" />
 <AlternatingRowStyle BackColor="White" />
 </asp:GridView>
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
 SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [Discontinued] FROM [Products]">
 </asp:SqlDataSource>
 <br />
 <asp:Button ID="btn_Send" runat="server" OnClick="btn_Send_Click" Text="Send Email" />
 </div>
 </form>
</body>
</html>

and in code behind add the following code :


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
 #region Method
 private string GridViewToHtml(GridView gv)
 {
 StringBuilder SB = new StringBuilder();
 StringWriter SW = new StringWriter(SB);
 HtmlTextWriter htmlTW = new HtmlTextWriter(SW);
 gv.RenderControl(htmlTW);
 return SB.ToString();
 }

private bool SendMail(string from, string subject)
 {
 try
 {
 string mailServerName = "smtp.gmail.com";
 string body = GridViewToHtml(GridView1);
 MailMessage message = new MailMessage(from, "email@gmail.com", subject, body);
 message.IsBodyHtml = true;
 SmtpClient smtp = new SmtpClient();
 smtp.Host = mailServerName;
 smtp.Host = "smtp.gmail.com";
 smtp.EnableSsl = true;
 smtp.UseDefaultCredentials = true;
 System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
 NetworkCred.UserName = "email@gmail.com";
 NetworkCred.Password = "*****";
 smtp.UseDefaultCredentials = true;
 smtp.Credentials = NetworkCred;
 smtp.Port = 587;
 smtp.Send(message);
 }
 catch (Exception ex)
 {
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('An Error Accured try again.');</script>");
 }
 return true;
 }
 public override void VerifyRenderingInServerForm(Control control)
 {

}
 #endregion

protected void Page_Load(object sender, EventArgs e)
 {

}
 protected void btn_Send_Click(object sender, EventArgs e)
 {
 if (SendMail("noor3rb@hotmail.com", "Send Gridview in Email"))
 {
 // Sucess to send Email
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('Email has been sent.');</script>");
 }
 else
 {
 // Fail to send Email
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('An Error Accured try again.');</script>");
 }
 }
}

2) In Web.Config add connectionstring


<connectionStrings>
 <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Hope this helps

Good Luck.

Categories: ASP.Net