AJAX Enabled WebParts and FireFox Drag and Drop

WebParts Cross- browser drag and drop is a very common issues on ASPNET WebPart Framework.. Basically WebParts doesn't support the Drag and Drop feature in Firefox browsers and this known to be a BUG for ASPNET Webpart Framework.. To get things working in all browsers including the cross browser drag-and-drop feature then you would need to use Visual studio 2008 / VWD 2008 with latest version of the Microsoft ASPNET Futures (AJAX Control Toolkit 3.5)..

For more detail information then i would suggest you to read the following article below

http://waitink.blogspot.com/2008/06/ajax-web-parts-part-1-drag-and-drop.html

We also discuss the issues in the following links below

http://forums.asp.net/t/1277540.aspx

http://forums.asp.net/p/1087200/1943716.aspx#1943716

Set Background Color for each ListItems of the DropDownList

The following snippet below describes on how we are going to set the ListItem Background Color based on the Color name displayed in the DropDownList


ASPX MARKUP OF DROPDOWNLIST


<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" OnLoad="DropDownList1_Load">
        <asp:ListItem Value="-1">Select</asp:ListItem>
        <asp:ListItem Value="0">Red</asp:ListItem>
        <asp:ListItem Value="1">Blue</asp:ListItem>
        <asp:ListItem Value="2">Green</asp:ListItem>
        <asp:ListItem Value="3">Violet</asp:ListItem>
</asp:DropDownList>

RELEVANT CODES
protected void DropDownList1_Load(object sender, EventArgs e)
{
        for (int i = 0; i < DropDownList1.Items.Count; i++)
        {
            DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
           
        }
}

That's it!

Formatting String number values to money in ASPNET

The following are the ways on how to format string number values into a money format with decimals.

Option 1: - Using String.Format method

C#

double formatToMoney;
string num = "1500";
if (double.TryParse(num, out formatToMoney))
{
            string newNum = String.Format("{0:c}", formatToMoney);
            Response.Write(newNum);
}

VB.NET

Dim formatToMoney As Double
Dim num As String = "1500"
If Double.TryParse(num, formatToMoney) Then
    Dim newNum As String = String.Format("{0:c}", formatToMoney)
    Response.Write(newNum)
End If

Option 2: using .ToString() method

C#

double formatToMoney;
string num = "1500";
if (double.TryParse(num, out formatToMoney))
{
            string newNum = formatToMoney.ToString("$#,###.00");
            Response.Write(newNum);
}

VB.NET

Dim formatToMoney As Double
Dim num As String = "1500"
If Double.TryParse(num, formatToMoney) Then
    Dim newNum As String = formatToMoney.ToString("$#,###.00")
    Response.Write(newNum)
End If

That's it! Happy Coding!

Limiting the Data being displayed in the GridView and Display Tooltip

The following snippet below describes on how we are going to limit the Text displayed in the boundfield column of the GridView and display the original data in the ToolTip when user hovers the mouse for a particular cell.

C#

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ViewState["OrigData"] = e.Row.Cells[0].Text;
                if (e.Row.Cells[0].Text.Length >= 30) //Just change the value of 30 based on your requirements
                {
                    e.Row.Cells[0].Text = e.Row.Cells[0].Text.Substring(0, 30) + "...";
                    e.Row.Cells[0].ToolTip = ViewState["OrigData"].ToString();
                }

             }

}

VB.NET

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        ViewState("OrigData") = e.Row.Cells(0).Text
        If e.Row.Cells(0).Text.Length >= 30 Then  'Just change the value of 30 based on your requirements
            e.Row.Cells(0).Text = e.Row.Cells(0).Text.Substring(0, 30) + "..."
            e.Row.Cells(0).ToolTip = ViewState("OrigData").ToString()
        End If
    End If
End Sub 

That simple! Hope it Helps!

Passing Multiple Querystring values with Response.Redirect method

Here's an example on how to pass Multiple querystrings in the page..

Page1

protected void Button1_Click(object sender, EventArgs e)
{
        string strName = "VINZ";
        string strAddress = "CEBU";
        string strDate = DateTime.Now.ToShortDateString();
        Response.Redirect(string.Format("TestNasad2.aspx?param1={0}&param2={1}&param3={2}",strName,strAddress,strDate));

}

The on Page2 you can get each values this way below

protected void Page_Load(object sender, EventArgs e)
{
        if ((Request.QueryString["param1"] != null && Request.QueryString["param2"] != null) && Request.QueryString["param3"] != null)
        {
            string name = Request.QueryString["param1"];
            string address = Request.QueryString["param2"];
            string date = Request.QueryString["param3"];

        }
}

Hope this Helps!

Custom Login: Validating UserName and Password using the ADO.NET way

The snippet below describes on how we are going to validate the user credentials being supplied by the end user in Login page using the ADO.NET way..

C#

protected void ValidateUserInfo(string user, string pass)
{
  
    SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE");
    string sql = "SELECT * FROM TableName WHERE UserID = @username AND Password = @password";
    SqlCommand cmd = new SqlCommand(sql,connection);
    cmd.Parameters.AddWithValue("@username", user);
    cmd.Parameters.AddWithValue("@password", pass);
    connection.Open();
 
    DataTable dt = new DataTable();
    SqlDataAdapter ad = new SqlDataAdapter(cmd);
    ad.Fill(dt);
    if (dt.Rows.Count > 0) { //check if the query returns any data
        //Valid Username and Password
        Response.Redirect("Default.aspx");
    }
    else
    {
        Response.Write("INVALID Username and Password, Try Again!");
    }
    connection.Close();   
}
protected void Button1_Click(object sender, EventArgs e)
{
  ValidateUserInfo(TextUserName.Text.Trim(), TextPassword.Text.Trim());
}

VB.NET

Protected Sub ValidateUserInfo(ByVal user As String, ByVal pass As String)
   
    Dim connection As New SqlConnection("YOUR CONNECTION STRING HERE")
    Dim sql As String = "SELECT * FROM TableName WHERE UserID = @username AND Password = @password"
    Dim cmd As New SqlCommand(sql, connection)
    cmd.Parameters.AddWithValue("@username", user)
    cmd.Parameters.AddWithValue("@password", pass)
    connection.Open()
   
    Dim dt As New DataTable()
    Dim ad As New SqlDataAdapter(cmd)
    ad.Fill(dt)
    If dt.Rows.Count > 0 Then
        'check if the query returns any data
        Response.Redirect("Default.aspx")
    Else
        Response.Write("INVALID Username and Password, Try Again!")
    End If
    connection.Close()
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1_Click
    ValidateUserInfo(TextUserName.Text.Trim(), TextPassword.Text.Trim())
End Sub

That simple! Happy Coding!

Bind TextBox and Label Control with Data from database

This sample snippet below describes on how we are going to Populate a TextBox and Label control in the page based on the data associated per user using the ADO.NET way..

C#

private void getData(string user)
{
    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE");
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("SELECT * from TABLE1 WHERE UserID = @username", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlCmd.Parameters.AddWithValue("@username",user);
    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
           TextBox1.Text = dt.Rows[0]["ColumnName1"].ToString(); //Where ColumnName is the Field from the DB that you want to display
           TextBox2.Text = dt.Rows[0]["ColumnName2"].ToString();
           Label1.Text = dt.Rows[0]["ColumnName3"].ToString();
           Label2.Text = dt.Rows[0]["ColumnName4"].ToString();
    }
        connection.Close();
}

protected void Page_Load(object sender, EventArgs e)
{

   if (!Page.IsPostBack){
    getData(this.User.Identity.Name);
   }

}

VB.NET

Private Sub getData(ByVal user As String)
    Dim dt As New DataTable()
    Dim connection As New SqlConnection("YOUR CONNECTION STRING HERE")
    connection.Open()
    Dim sqlCmd As New SqlCommand("SELECT * from TABLE1 WHERE UserID = @username", connection)
    Dim sqlDa As New SqlDataAdapter(sqlCmd)
   
    sqlCmd.Parameters.AddWithValue("@username", user)
    sqlDa.Fill(dt)
    If dt.Rows.Count > 0 Then
        TextBox1.Text = dt.Rows(0)("ColumnName1").ToString()  'Where ColumnName is the Field from the DB that you want to display
        TextBox2.Text = dt.Rows(0)("ColumnName2").ToString()
        Label1.Text = dt.Rows(0)("ColumnName3").ToString()
        Label2.Text = dt.Rows(0)("ColumnName4").ToString()
    End If
    connection.Close()
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsPostBack Then
        getData(Me.User.Identity.Name)
    End If
End Sub

Note: Don't forget to declare the following Namespaces below for you to make it work.

For C#:
Using System.Data;
Using System.Data.SqlClient;


For VB.NET
Imports System.Data;
Imports System.Data.SqlClient;

That simple! Hope this will be useful for you..

Manually Binding DropDownList based on the value selected on the first DropDownList

I decided to write this article because I always encounter this kind of problem in the ASPNET Forum . So here's a sample (one way) solution on how to populate the second DropDownList based on the value selected on the first DropDownList using the ADO.NET way.

Assuming that DropDownList1 contains the list of countries and we need to populate the list of States in a particular country based on the first DropDownList selection.

protected void PopulateDropDownList1(){
    string queryString = "SELECT * FROM Table1";
    SqlClient.SqlConnection connection = new SqlClient.SqlConnection("Data Source=HCISSQL2;Initial Catalog=...;User ID=apps;Password=...");
    SqlClient.SqlCommand command = new SqlClient.SqlCommand(queryString, connection);
       
    connection.Open();
  
    DataTable dt = new DataTable();
    SqlDataAdapter ad = new SqlDataAdapter(command);
    ad.Fill(dt);
    if (dt.Rows.Count > 0) {

    DropDownList1.DataSource = dt;
    DropDownList1.DataTextField = "CountryName";
    DropDownList1.DataValueField = "CountryName";
    DropDownList1.DataBind();
    }
   
    connection.Close();
  
}
protected void PopulateDropDownList2(string country)
{
   
    string queryString = "SELECT States FROM FROM Table2 WHERE Country = @country";
    SqlClient.SqlConnection connection = new SqlClient.SqlConnection("YOUR CONNECTION STRING HERE");
    SqlClient.SqlCommand command = new SqlClient.SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@country", country);
    connection.Open();
  
    DataTable dt = new DataTable();
    SqlDataAdapter ad = new SqlDataAdapter(command);
    ad.Fill(dt);

    DropDownList1.Items.Clear();
    if (dt.Rows.Count > 0) {

    DropDownList2.DataSource = dt;
    DropDownList2.DataTextField = "States";
    DropDownList2.DataValueField = "States";
    DropDownList2.DataBind();
    }
    connection.Close();
   
}

protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   
 PopulateDropDownList2(DropDownList1.Value.ToString());
   
}
protected void Page_Load(object sender, System.EventArgs e)
{
   
    if (!Page.IsPostBack) {
       
        PopulateDropDownList1();
       
    }
}

NOTE: Don't forget to add the following Namespaces below for you to make it work

Using System.Data;

Using System.Data.SqlClient;

Also don't forget to set AutoPostBack to TRUE in your first DropDownList to fire up the SelectedIndexChanged event

 

Another Solution:

You can also use Cascading DropDownList .. see below for demo

http://www.asp.net/learn/ajax-videos/video-77.aspx

That simple!

WEBPART: Count the number of Closed WebParts within PageCatalogPart

The following snippets below checks whether the PageCatalogPart Control contains any available WebParts in a page that have been closed in the page..

C#
protected void PageCatalogPart1_Load(object sender, EventArgs e)
{
        int count = 0;
        if (WebPartManager1.WebParts.Count > 0)
        {
            for (int i = 0; i < WebPartManager1.WebParts.Count; i++)
            {
                WebPart wp = (WebPart)WebPartManager1.WebParts[i];
                if (wp.IsClosed)
                {
                    Response.Write("Page Catalog contains Closed WebParts");
                    count++;
                }
            }
            Response.Write("<br/>Tolal closed WebParts: " + count.ToString());
        }
}

VB.NET

Protected Sub PageCatalogPart1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim count As Integer = 0
    If WebPartManager1.WebParts.Count > 0 Then
        For i As Integer = 0 To WebPartManager1.WebParts.Count - 1
            Dim wp As WebPart = DirectCast(WebPartManager1.WebParts(i), WebPart)
            If wp.IsClosed Then
                Response.Write("Page Catalog contains Closed WebParts")
                count += 1
            End If
        Next
        Response.Write("<br/>Tolal closed WebParts: " + count.ToString())
    End If
End Sub

Get the days difference between two Dates

Here's an example on how to get the date difference between two given dates using TimeSpan.

C#

protected void Page_Load(object sender, EventArgs e)
{
DateTime dFrom;
DateTime dTo;
string sDateFrom = "9/9/2007";
string sDateTo = "1/10/2008";
if (DateTime.TryParse(sDateFrom, out dFrom) && DateTime.TryParse(sDateTo, out dTo))
{
TimeSpan TS = dTo - dFrom;
int daysDiff = TS.Days;
Response.Write(daysDiff.ToString());
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = "9/9/2007"
Dim sDateTo As String = "1/10/2008"
If DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Dim TS As TimeSpan = dTo - dFrom
Dim daysDiff As Integer = TS.Days
Response.Write(daysDiff.ToString())
End If
End Sub
«December»
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910