Tuesday, January 17, 2012

How to Bind Data List With Product Images From Database


How to Bind With Data List:



<asp:DataList ID="DlProducts" runat="server" Height="138px" Width="416px" Font-Names="Verdana" Font-Size="Small">
   
 <ItemTemplate>
    <div style="border:1px solid black;" id ="divProd" runat=server>
        <table style="width: 550px">
        <tr align =left>
            <td rowspan="4" style="width: 126px;border:0px;" align =left>
                <asp:Label ID="LblProdId" runat ="server" CssClass="LabelStyle" Text='<%# DataBinder.Eval(Container.DataItem, "Product_id") %>' Width="200px" Font-Bold =true Visible=false ></asp:Label>
                <asp:Image ID="Img" runat="server" Height="60px" ImageUrl='<%# "Picture.aspx?id=" & Eval("Product_id")%>' Width="70px" />
               
                </td>
            <td style="width: 224px">
                        <asp:Label ID="ProdName" runat ="server" CssClass="LabelStyle" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' Width="200px" Font-Bold =true></asp:Label></td>
            <td style="width: 102px">
                            <asp:Label ID="LblQty" runat="server" Font-Names="Verdana" Font-Size="Small" Text="Quantity" Visible=false></asp:Label>
                            <asp:Label ID="LblWeight" runat="server" Font-Names="Verdana" Font-Size="Small" Text="Select Weight"></asp:Label>
                            </td>
            <td>
                            <asp:TextBox ID="txtqty" runat="server" Width="64px" Height=14px Text = "1" style="text-align:right;" OnTextChanged="txtqty_TextChanged" AutoPostBack="True" Visible =false></asp:TextBox>
                            <asp:DropDownList ID="DdlWeight" runat="server" Width = 70px Height = 19px  AutoPostBack ="true" OnSelectedIndexChanged ="DdlWeight_SelectedIndexChanged"
                               
                                DataSource = '<% #DdlBindWeight(Eval("Product_id"))%>' DataValueField = "data_id" DataTextField = "data"
                                Font-Size="12px" CssClass = "SetIndex"></asp:DropDownList>
                            </td>
        </tr>
        <tr>
            <td style="width: 224px">
                        <asp:Label ID="lblAmount" runat ="server" CssClass="LabelStyle" Text='<%# DataBinder.Eval(Container.DataItem, "Sales_Price") %>' Width="200px"></asp:Label>
                        <asp:Label ID="CalAmt" runat ="server" CssClass="LabelStyle" Text='<%# DataBinder.Eval(Container.DataItem, "Price") %>' Width="200px" Visible =false></asp:Label>
                        </td>
            <td style="width: 102px">
            </td>


        </tr>
        <tr>
            <td style="width: 224px; height: 21px">
                        <asp:Label ID="Label3" runat ="server" CssClass="LabelStyle" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>' Width="200px"></asp:Label></td>
            <td style="width: 102px; height: 21px">
            </td>
            <td style="height: 21px">
            </td>
        </tr>
        <tr>
            <td style="width: 224px">
            </td>
            <td style="width: 102px">
            </td>
            <td>
            </td>
        </tr>
    </table>             
          
</div>
 </ItemTemplate>
       
</asp:DataList>

How to Store and Display Image in Image Control

Some Times happens that we tries to Show in Image in Box using Image controls. Developes use different Kinds of Stretegies like to store the Photoes in Folder and Load Photo from this Folder. But It does not works Sometimes. The better way is to store image in database in Binary Format and show it on web page. Now How can we do it given below Steps:
1. Make Page Named Picture.aspx and Write this Code on its Load Event.



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim conn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionKoris"))
Dim sql1 As String = "Select Image from Product_master where Product_id='" & Request.QueryString("id") & "'"
        
 Dim cmd1 As New SqlCommand(sql1, conn)
 conn.Open()
        
 Dim dr As SqlDataReader = cmd1.ExecuteReader()
         
 If dr.Read() Then
            If dr("Image").ToString() <> System.DBNull.Value.ToString() Then
                
 Dim imageByte As Byte() = DirectCast(dr("Image"), Byte())
 If imageByte IsNot Nothing AndAlso imageByte.Length > 0 Then
                    Context.Response.ContentType = "image/jpeg"
                    Context.Response.BinaryWrite(imageByte)
                End If
            End If
        End If
        dr.Close()
        conn.Close()
    End Sub
How to Pass from Code Behind:
Note: TxtProdId.text is the Id of database table in which favor particulare image is contained.
ProdImg.ImageUrl = "Picture.aspx?id=" & Val(TxtProdId.Text)
How to Pass for bind in Gridview,Datalist,ListView,Datagrid etc. as Given Below: 

<asp:Image ID="Image2" runat="server" Height="80px" ImageUrl='<%# "Picture.aspx?id=" & Eval("Product_id")%>' Width="80px" />

Tuesday, January 3, 2012

Monday, January 2, 2012

How to Add day to a particular date and how to set Date format of a particular Date

TxtDate.Text = Now.Date.ToString("dd/MM/yyyy")
LblD1.Text = " " & Now.Date.AddDays(1).Day
LblD1.ToolTip = Now.Date.AddDays(1).Date.ToString("dd/MM/yyyy")

Function For Export Dataset To Excel Sheet

Public Sub ExportDataSetToExcel(ByVal ds As DataSet, ByVal filename As String)
  '--------Export Dataset To Excel---------------'
Dim attachment As String = "attachment; filename=" & filename & ".xls"
        Response.ClearContent()        Response.AddHeader("content-disposition",attachment)
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        ' create a string writer  
        Using sw As New StringWriter()
            Using htw As New HtmlTextWriter(sw)
                ' instantiate a datagrid  
                Dim dg As New DataGrid()
                dg.DataSource = ds.Tables(0)
                dg.HeaderStyle.Font.Bold = True
                dg.DataBind()
                dg.RenderControl(htw)
                Response.Write(sw.ToString())
                Response.[End]()
            End Using
        End Using
    End Sub

How to make single Selection of Radio Button in a Grid View using VB.net


Some time its happens in a Gridview have a column with more radio buttons but it do not select a single selection of a radio button. It selects all the radio buttons as you select it. For get Rid from this Problem. Given Below function can help you:


Protected Sub RdAdd_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
  Dim dr As GridViewRow
  Dim oldRow As RadioButton = GdvAdd.FindControl("rdadd")
  Dim count = 0
  'TextBox3667.Text = Request.Form("RDI")
  For Each dr In GdvAdd.RowsoldRow = CType(GdvAdd.Rows(count).FindControl("rdadd"),
RadioButton)oldRow.Checked = False
            count += 1
        Next
        'ADD Old Value
        Dim NewRow As RadioButton = sender
        Dim row As GridViewRow = NewRow.NamingContainer
        NewRow.FindControl("rdadd")
        NewRow.Checked = True
    End Sub

How to Set the position of Page when post back

Some times it happens that our web have a Grid View and Data Grid Contained lots of rows. Which makes Scrolling in Your page. If we clicks on a row and its redirect to another page then The Grid View and Data Grid Becomes Comes on Starting Position of Gridview or DataGrid. For Setting Your Grid View and Data Grid On Last Row Position the Given Below Property can be used.

Property of Page:

MaintainScrollPositionOnPostback ="true"


Example:




<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Reports.aspx.vb" Inherits="Reports" MaintainScrollPositionOnPostback ="true" %>


Note: If your Grid is inside the Update panel then will not work.

How To Show the Header of GridView When Data Source is nothing

If ds.Tables(0).Rows.Count > 0 Then
    GdvAdd.DataSource = ds.Tables("AddTbl")
    GdvAdd.DataBind()
Else
   ds.Tables(0).Rows.Add(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
   GdvAdd.DataSource = ds.Tables("AddTbl")
   GdvAdd.DataBind()
   GdvAdd.Rows(0).Visible = False
End If

How to Select All Check Boxs of Gridview row on Single Selection of Header Check Box using JavaScript

function chkall(ival)
{
   var f= document.getElementById("GdvStatus");   
for(var i=0; i<f.getElementsByTagName("input").length ;i++ )
 {
if(f.getElementsByTagName("input").item(i).type == "checkbox" )
   {       
                     f.getElementsByTagName("input").item(i).checked=ival;                
   }  
  } 
}

How To Call:

<asp:CheckBox ID="ChkSelectAll" onclick="chkall(this.checked)" runat="server" />  

How to set Short Cut key in Asp.net Application Using Java Script

//This line is very Importance
 
document.onkeydown = checkKeycode

function checkKeycode(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else
    if (e.which == 113) // for F2 Key of Key board
    //keycode = e.which;
    //alert("keycode: " + keycode);
    document.getElementById("ImgBtnRoute").click();


}

How to Validate server side controls in Asp.net using Custom Validator

Some times we require that the page should not be submitted when server side control is being used.

We have two kinds of server side control validation as given below:
1). TextBox Custom Validation
2). File Upload control custom Validation


1). TextBox Custom Validation

Java Script :

function ConfirmApproval(source, args)
    {
   
  //debugger;
        var t1 = document.getElementById("TxtCurrDate").value;
        var t2 = args.Value//document.getElementById("TxtHidden").value;
        if(args.Value == t1)
            {
//            alert('hello');
//            }
                var r=confirm("The Price on this Date are already in Database, Do Your Really wants to Update !");
                if (r==true)
                  {
                        args.IsValid = true;
                        return;
//                      return true;
                  }
                else
                  {    
                        args.IsValid = false;
                        return;
//                        return false;
                  }       
        }   

    }



Custom Validator control Validation:

<asp:CustomValidator id="CheckUpdate"
        runat="server"
        ControlToValidate="TxtHidden"
        ValidateEmptyText="true"
        ClientValidationFunction="ConfirmApproval"
        Display="None">custom validator</asp:CustomValidator><br />



2). File Upload control custom Validation


Java Script :

function ValidateUpl(source, args)
    {  
        //debugger;
        var fuData = document.getElementById('<%= UplFile.ClientID %>');
        var FileUploadPath = fuData.value;

            if(FileUploadPath =='')
                {
                 alert('Please choose Excel file for update Rate list.');
                 args.IsValid = false;
                }
                 else
                {
                 var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

                if (Extension == "xls")
                {
                args.IsValid = true; // Valid file type
                 }
                else
                {
                alert('Please choose Excel file for Update Rate list.');
                args.IsValid = false; // Not valid file type
                }
                }

    }


Custom Validator control Validation:

<asp:CustomValidator ID="CustomValidator1"
        runat="server"
        ClientValidationFunction="ValidateUpl"
        ControlToValidate="UplFile"
        ErrorMessage="CustomValidator" Display ="None"
        ValidateEmptyText="True"></asp:CustomValidator