Yasserzaid’s Weblog

May 28, 2009

FindControl inside FormView

Filed under: ASP.Net — yasserzaid @ 6:55 am

Hi

try this example to FindControl inside FormView

protected void FormView1_DataBound(object sender, EventArgs e)
{
        //Check for its current mode
        if (FormView1.CurrentMode == FormViewMode.ReadOnly)
        {
            //Check the RowType to where the Control is placed
            if (FormView1.Row.RowType == DataControlRowType.DataRow)
            {
                //Just Changed the index of cells based on your requirement
                Label lbl = (Label)FormView1.Row.Cells[0].FindControl("Label1");
                if (lbl= !null)
                {
                    lbl.Text = "Found a Label";
                }

            }
        }
}

Hope this helps

Good Luck

May 26, 2009

Validate Minimum Length of Textbox

Filed under: ASP.Net — yasserzaid @ 10:43 am

Hi

try this example to Validate Minimum Length of Textbox using Regular Expression Validator Control

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <asp:RegularExpressionValidator
       ID="valUserName" runat="server" ControlToValidate="TextBox1"
       Display="Dynamic" ErrorMessage="Minimum length 6 characters"
       ForeColor="" ValidationExpression=".{6}.*" ></asp:RegularExpressionValidator>

Hope this helps

Good Luck

Create Watermark TextBox using JavaScript

Filed under: ASP.Net, Javascript — yasserzaid @ 8:54 am

Hi

try this example to create Watermark Textbox using javascript

<script type = "text/javascript">
    var defaultText = "Enter your text here";
    function WaterMark(txt, evt)
    {
        if(txt.value.length == 0 && evt.type == "blur")
        {
            txt.style.color = "gray";
            txt.value = defaultText;
        }
        if(txt.value == defaultText && evt.type == "focus")
        {
            txt.style.color = "black";
            txt.value="";
        }
    }
</script>

<asp:TextBox ID="txt_Name" runat="server" Text = "Enter your Name here"
    ForeColor = "Gray" onblur = "WaterMark(this, event);"
    onfocus = "WaterMark(this, event);">
</asp:TextBox>

we can access onblur and onfocus events of textbox in code behind

C#
txt_Name.Attributes.Add("onblur", "WaterMark(this, event);");
txt_Name.Attributes.Add("onfocus", "WaterMark(this, event);");

Hope this helps

Good Luck

May 20, 2009

Change Textbox Border on focus

Filed under: ASP.Net, CSS, Javascript — yasserzaid @ 7:56 am

Hi

try this example to Change Textbox Border on focus

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
   <script type ="text/javascript">
    function Change(obj, evt)
    {
        if(evt.type=="focus")
            obj.style.borderColor="red";
        else if(evt.type=="blur")
           obj.style.borderColor="black";
    }
   </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server" onfocus ="Change(this, event)"
        onblur ="Change(this, event)"></asp:TextBox>
    </form>
</body>
</html>

you can also try this example using CSS

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <style type ="text/css">
        .onfocus
        {
            border-color:red;
        }
        .onblur
        {
            border-color:;
        }
    </style>
   <script type ="text/javascript">
    function Change(obj, evt)
    {
        if(evt.type=="focus")
            obj.className ="onfocus";
        else if(evt.type=="blur")
           obj.className ="onblur";
    }
   </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"   onfocus ="Change(this, event)"
        onblur ="Change(this, event)"></asp:TextBox>
    </form>
</body>
</html>

Hope this helps

Good Luck

May 16, 2009

Show Header and Footer of GridView when no Data returned

Filed under: ASP.Net — yasserzaid @ 1:11 pm

Hi

try this example to Show Header and Footer of GridView when no Data returned:

private void ShowNoResultFound(DataTable source, GridView gv)
    {
        source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable
        // Bind the DataTable which contain a blank row to the GridView
        gv.DataSource = source;
        gv.DataBind();
        // Get the total number of columns in the GridView to know what the Column Span should be
        int columnsCount = gv.Columns.Count;
        gv.Rows[0].Cells.Clear();// clear all the cells in the row
        gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
        gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
        //You can set the styles here
        gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
        gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
        gv.Rows[0].Cells[0].Font.Bold = true;
        //set No Results found to the new added cell
        gv.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
    }

private void BindGridView()
{
        DataTable dt = new DataTable(string user);
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT* FROM Orders WHERE UserID = @User";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            sqlCmd.Parameters.AddWithValue("@User", user);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0) //Check if DataTable returns data
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            Else //else if no data returned from the DataTable then

            {    //call the method ShowNoResultFound()
                ShowNoResultFound(dt,GridView1);
            }
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
        }

        finally

        {
            connection.Close();
        }
}

Hope this helps

Good Luck

Validate ListBox

Filed under: ASP.Net — Tags: — yasserzaid @ 1:04 pm

Hi

try this example to validate ListBox control using CustomValidator Control

<script type="text/javascript">
function ValidarListaSeleccionada(sender, args)
{
  args.IsValid = document.getElementById(sender.controltovalidate).options.length>0;
}   
</script>

<div>
        <asp:ListBox ID="ListBox1" runat="server">
        </asp:ListBox>
        <br />
        <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidarListaSeleccionada" OnServerValidate="CustomValidator1_ServerValidate"            ControlToValidate="ListBox1" ErrorMessage="Select One." ValidateEmptyText="True"></asp:CustomValidator><br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Send" />
</div>

And the server side function, just in case

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = lBox.Items.Count > 0;
}

Hope this helps

Good Luck

Drag DIV with Javascript

Filed under: ASP.Net, Javascript — yasserzaid @ 12:48 pm

Hi

try this example to drag DIV using  javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MoveDIV.aspx.cs" Inherits="MoveDIV" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">

<title>Untitled Page</title>
<style type="text/css">
.dragclass{
position : relative;
cursor : move;
}
</style>
<script type="text/javascript">
//Drag and Drop script - <a href="http://www.btinternet.com/~kurt.grigg/javascript">http://www.btinternet.com/~kurt.grigg/javascript</a>

if  (document.getElementById){

(function(){

//Stop Opera selecting anything whilst dragging.
if (window.opera){
document.write("<input type='hidden' id='Q' value=' '>");
}

var n = 500;
var dragok = false;
var y,x,d,dy,dx;

function move(e){
if (!e) e = window.event;
 if (dragok){
  d.style.left = dx + e.clientX - x + "px";
  d.style.top  = dy + e.clientY - y + "px";
  return false;
 }
}

function down(e){
if (!e) e = window.event;
var temp = (typeof e.target != "undefined")?e.target:e.srcElement;
if (temp.tagName != "HTML"|"BODY" && temp.className != "dragclass"){
 temp = (typeof temp.parentNode != "undefined")?temp.parentNode:temp.parentElement;
 }
if (temp.className == "dragclass"){
 if (window.opera){
  document.getElementById("Q").focus();
 }
 dragok = true;
 temp.style.zIndex = n++;
 d = temp;
 dx = parseInt(temp.style.left+0);
 dy = parseInt(temp.style.top+0);
 x = e.clientX;
 y = e.clientY;
 document.onmousemove = move;
 return false;
 }
}

function up(){
dragok = false;
document.onmousemove = null;
}

document.onmousedown = down;
document.onmouseup = up;

})();
}//End.
</script>  
</head>
<body>
    <form id="form1" runat="server">
        <div id="test" class="dragclass" style="position:absolute;top:330px;left:160px;height:20px;width:150px;background-color:#ff0000;color:#ffffff">
Div: Absolute position
</div>

</form>
</body>
</html>

Hope this helps

Good Luck

Pass multiple values to Command Argument

Filed under: ASP.Net — yasserzaid @ 12:45 pm

Hi

try this example to Pass multiple values to Command Argument

<asp:TemplateField>
     <ItemTemplate>                          
 <asp:Button ID="btnTest" runat="Server" CommandName="Test" Text="Select"
 CommandArgument='<%#Eval("carid") + ","+Eval("year") %>' />                
     </ItemTemplate>                 
 </asp:TemplateField>

 in code behind :-

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)   
{       
if (e.CommandName == "Test")       
{           
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });      
string carid = commandArgs[0];      
string year = commandArgs[1];       
}   
}

Hope this helps

Good Luck

Easy SQL If Record Exists, Update It. If Not, Insert It.

Filed under: SQL Server — yasserzaid @ 12:43 pm

Hi

try this example :-

CREATE PROCEDURE dbo.spAddUser 
(    @UserID AS int,
     @FirstName AS varchar(50),
     @LastName AS varchar(50)    
)
AS
     BEGIN
          DECLARE @rc int
            UPDATE [Users]           
     SET FirstName = @FirstName, LastName = @LastName
           WHERE UserID = @UserID    
      /* how many rows were affected? */
         SELECT @rc = @@ROWCOUNT 
           IF @rc = 0 
             BEGIN    
               INSERT INTO [Users]                              
  (FirstName, LastName)                        
  VALUES(@FirstName, LastName)           
  END           
 END

Hope this helps

Good Luck

Resetting Password with ASP.NET 2.0 Membership

Filed under: ASP.Net — Tags: — yasserzaid @ 12:41 pm

Hi

If you ever have wanted to be able to programmatically change (reset) a users password while at the same time continuing to be

able to use the question and answer feature, this post is for you.  The problem is that if you use code like this:

 string username = "username";
 string password = "pass@word";
 MembershipUser mu = Membership.GetUser(username);
 mu.ChangePassword(mu.ResetPassword(), password);

You will find that if you have in your web.config requiresQuestionAnswer=”true”, you will get an error when you try and reset the

password.  The elegant solution to this is to create an additional membeship tag in your web.config and reference it when you

change passwords.  That is, add another provider like this:

<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
    <clear/>
    <add name="SqlMembershipProviderOther" type="SqlProviderOneShot.SqlMembershipProvider"
    requiresQuestionAndAnswer="false"
     connectionStringName="ConnectionString" applicationName="/"
    enablePasswordRetrieval="false" enablePasswordReset="true"
    requiresUniqueEmail="true" passwordFormat="Hashed"
    minRequiredNonalphanumericCharacters="0" writeExceptionsToEventLog="false"
    minRequiredPasswordLength="1" passwordStrengthRegularExpression=""
    passwordAttemptWindow="10" maxInvalidPasswordAttempts="8"/>
</providers>
</membership>

Then, when you change your password, reference it as follows:

string username = "username";
string password = "pass@word";
MembershipUser mu = Membership.Providers["SqlMembershipProviderOther"].GetUser(username);
mu.ChangePassword(mu.ResetPassword(), password);

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.