Monday, June 29, 2009

0

ASP.NET Images in Gridview/DataList using objectdatasource

In this example i am going to explain how to display Images in GridView or DataList using ObjectDataSource.

For this first of all we need to create a Object to populate gridview or DataList.
Right click on solution explorer and add new class, name it whatever you want to.



In this class write a method to populate GridView, i'm creating a DataTable and adding some records.

The C# code behind

public DataTable GetData()
{
  DataTable dt = new DataTable();
  dt.Columns.Add(new DataColumn
                ("PictureID", typeof(int)));
  dt.Columns.Add(new DataColumn
                ("PictureURL", typeof(string)));
  dt.Columns.Add(new DataColumn
                ("Title", typeof(string)));

        DataRow dr = dt.NewRow();
        dr["PictureID"] = 1;
        dr["PictureURL"] = ResolveUrl
                ("~/Images/Ball1.gif");
        dr["Title"] = "FootBall";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["PictureID"] = 2;
        dr["PictureURL"] = "~/Images/Mobiles.jpg";
        dr["Title"] = "Mobile Phones";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["PictureID"] = 3;
        dr["PictureURL"] = "~/Images/Watch.jpg";
        dr["Title"] = "Watches";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["PictureID"] = 4;
        dr["PictureURL"] = "~/Images/Perfumes.jpg";
        dr["Title"] = "Perfumes";
        dt.Rows.Add(dr);
        return dt;
    }

VB.NET code behind
Public Function GetData() As DataTable
    Dim dt As New DataTable()
    dt.Columns.Add(New DataColumn("PictureID", GetType(Integer)))
    dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
    dt.Columns.Add(New DataColumn("Title", GetType(String)))
    
    Dim dr As DataRow = dt.NewRow()
    dr("PictureID") = 1
    dr("PictureURL") = ResolveUrl("~/Images/Ball1.gif")
    dr("Title") = "FootBall"
    dt.Rows.Add(dr)
    
    dr = dt.NewRow()
    dr("PictureID") = 2
    dr("PictureURL") = "~/Images/Mobiles.jpg"
    dr("Title") = "Mobile Phones"
    dt.Rows.Add(dr)
    
    dr = dt.NewRow()
    dr("PictureID") = 3
    dr("PictureURL") = "~/Images/Watch.jpg"
    dr("Title") = "Watches"
    dt.Rows.Add(dr)
    
    dr = dt.NewRow()
    dr("PictureID") = 4
    dr("PictureURL") = "~/Images/Perfumes.jpg"
    dr("Title") = "Perfumes"
    dt.Rows.Add(dr)
    Return dt
End Function

Now go to design view of the page and drag a GridView from toolbox.

Steps to create ObjectDataSource

Click on smart tag of gridview and select Choose Data Source > New DataSource

From next screen select Object, Click on OK
In next screen, choose your Object (the class file we created earlier )_ from the dropdown, Click on next.

In define data methods screen, choose your method for select statement you wrote in the class file(in our case it is GetData(),Return DataTable), Click on finish.



Now click on smart tag of GridView and Click on Edit Columns.

Uncheck the Auto-Generate field checkBox at bottom left of screen.



From the box at top left add two BoundField and 1 ImageField as shown in figure
Select first Bound field and change HeaderText property to "Picture ID" and DataField property to PictureID.


Repeat same for second bound field and for Title.
Select the ImageField and set DataImageUrlField property to PictureURL.

Complete HTML source of page will look like this
<asp:GridView ID="GridView1" Runat="server" 
              AutoGenerateColumns="False" 
              BorderWidth="1px" CellPadding="3" 
              BorderStyle="None" 
              BorderColor="#CCCCCC" 
              DataSourceID="ObjectDataSource1" 
              AllowPaging="True" PageSize=3>
<PagerStyle ForeColor="#000066" HorizontalAlign="Left" 
            BackColor="White">
</PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True" 
             BackColor="#006699">
</HeaderStyle>
<Columns>
<asp:BoundField HeaderText="Picutre ID" 
                DataField="PictureID">
<ItemStyle HorizontalAlign="Center" 
           VerticalAlign="Middle">
</ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Title" DataField="Title">
</asp:BoundField>
<asp:ImageField DataImageUrlField="PictureURL">
</asp:ImageField>
</Columns>
<SelectedRowStyle ForeColor="White" Font-Bold="True" 
                  BackColor="#669999"></SelectedRowStyle>
<RowStyle ForeColor="#000066"></RowStyle>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" 
                      runat="server" 
                      SelectMethod="GetData"
                      TypeName="ImagesInGridView">
</asp:ObjectDataSource>

Now save the project, build it and run it.

Hope this helps


Related Posts:
Insert Delete Edit Update GridView with ObjectDataSource

Insert Edit Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate

Edit or update multiple records/rows in gridview with checkbox

Delete multiple rows in Gridview with checkbox and delete confirmation Javascript

Add Auto Number Column in GridView or DataList

Continue Reading...

Wednesday, June 17, 2009

3

ASP.NET Read write word document with FileStream StreamWriter

In this article i am going to describe how to read and write to ms word file or document in ASP.NET using FileStream, StreamReader and StreamWriter.

For this i've added a textbox for input text to be written in word document and a button to write, same for reading text from word file.

The word file created is saved in a folder named document in root of application. which can be changed to desired location.



html source of the page look like
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<asp:Button ID="Button1" runat="server" 
                         onclick="Button1_Click" 
                         Text="Click to write to word" />
<br />
<asp:TextBox ID="TextBox2" runat="server">
</asp:TextBox>
<asp:Button ID="Button2" runat="server" 
                         onclick="Button2_Click" 
                         Text="Read Word Document" />
</div>
</form>
To use Filestream we need to add System.IO namespace

C# code behind
}
protected void Button1_Click(object sender, EventArgs e)
{
  //string path = @"C:\Test.doc";
  string strPath = Request.PhysicalApplicationPath 
                   + "\\document\\Test.doc";
            
  string strTextToWrite = TextBox1.Text; 
  FileStream fStream =  File.Create(strPath);  
  fStream.Close(); 
  StreamWriter sWriter = new StreamWriter(strPath); 
  sWriter.Write(strTextToWrite); 
  sWriter.Close(); 
}

protected void Button2_Click(object sender, EventArgs e)
{
 string strPath = Request.PhysicalApplicationPath 
                  + "\\document\\Test.doc";
 FileStream fStream = new FileStream
            (strPath, FileMode.Open, FileAccess.Read);
 StreamReader sReader = new StreamReader(fStream);
 TextBox2.Text = sReader.ReadToEnd();
 sReader.Close();
}

VB.NET code
Protected Sub Button1_Click
         (ByVal sender As Object, ByVal e As EventArgs)
    'string path = @"C:\Test.doc";
    Dim strPath As String = Request.PhysicalApplicationPath 
                            & "\document\Test.doc"
    
    Dim strTextToWrite As String = TextBox1.Text
    Dim fStream As FileStream = File.Create(strPath)
    fStream.Close()
    Dim sWriter As New StreamWriter(strPath)
    sWriter.Write(strTextToWrite)
    sWriter.Close()
End Sub

Protected Sub Button2_Click
         (ByVal sender As Object, ByVal e As EventArgs)
    Dim strPath As String = Request.PhysicalApplicationPath 
                            & "\document\Test.doc"
    Dim fStream As New FileStream
                 (strPath, FileMode.Open, FileAccess.Read)
    Dim sReader As New StreamReader(fStream)
    TextBox2.Text = sReader.ReadToEnd()
    sReader.Close()
End Sub
 

hope this helps

Continue Reading...

Friday, June 12, 2009

1

ASP.NET Login Control with custom membership provider database

If you want to use Login Control of ASP.NET with Custom DataBase and custom membership Provider than follow the steps mentioned in this article.

In this example i m going to describe how to change and use custom Database with Login Control in ASP.NET.

First of all you need to create DataBase schema for membership.
For this create a DataBase in sql server with any name you want.
Now open Visual studio command prompt and type aspnet_regsql , press enter
this will open wizard window to setup database for membership provider

Alternatively you can Go to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 and run aspnet_regsql.exe from there
Follow the steps according to images
 
 Choose your Database Server and DataBase Name 

Now open web.config file and write below mentioned code 
Add connection string
<connectionStrings>
    <add name="ConnectionString" 
    connectionString="server=AVDHESH\SQLEXPRESS;
    database=CustomMembership;uid=amit;password=password;"/>    
  </connectionStrings>
Now add this code in System.web section of web.config
<roleManager defaultProvider="CustomProvider">
 <providers>
 <add connectionStringName="ConnectionString" 
      name="CustomProvider"
 type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>

<membership defaultProvider="CustomMembershipProvider">
<providers>
<add name="CustomMembershipProvider"
     type="System.Web.Security.SqlMembershipProvider"
     connectionStringName="ConnectionString" />
</providers>
</membership>

After this click on website menu in Visual Studio and select ASP.NET Configuration 
GO to Provider Tab and click on Select a different provider for each feature (advanced) option 



Now create users by going to security tab 
Your custom membership provider with your own custom databse configuration is done 
Build and test the application 

Continue Reading...

Tuesday, June 9, 2009

1

ASP.NET Insert Edit Update GridView with ObjectDataSource

In this example i am going to describe how to edit and update GridView using ObjectDataSource

For this i've created a simple database with a table named Details having 3 columns ID,Name and Location.

Open Visual studio and create a new website. Now right click on solution explorer and select add new Item > Sql Database > name it DataBase.mdf

Create a table with columns i mentioned above in this Database.

Right click on Solution explorer and Select add new Item > choose DataSet from the dialog box

To learn how to configure database connection and connection string for this example read my article
Insert Edit Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate


Right click on DataSet designer window and select Add > Table Adapter 


Follow the steps according to images


Use query builder to create sql statements or write ur own

Now Right click on TableAdapter and add Query for Update statement , choose Update radio button in next dialog box
Write your Update Statement


Click on finish and save the solution 

Now go to toolbox and drag a GridView on the design view of page.
Click on smart tag of GridView and choose new DataSource > Select ObjectDataSource

Select tableAdapter from the dropdown menu


Assign methods for select and update command in next dialog box

 
 
 Save the solution 


Now go to html markup of the page and change the html code of gridview according to code written below to implement ItemTemplate and EditItemTemplate

I'm using Bind method in EditItemTemplate of GridView so we do not need to write and code in CodeBehind

The html source of page should look like


<div>
<asp:GridView ID="GridView1" runat="server" 
                             AutoGenerateColumns="False" 
                             DataSourceID="ObjectDataSource1">
          
     <Columns>
     <asp:CommandField ShowEditButton="true" />
     <asp:TemplateField HeaderText="ID" SortExpression="ID">
     <EditItemTemplate>
     <asp:TextBox ID="txtID" runat="server" ReadOnly="true" 
                  Text='<%# Bind("ID") %>'>
     </asp:TextBox>
     </EditItemTemplate>       
     <ItemTemplate>
     <asp:Label ID="lblID" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("ID") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     
     <asp:TemplateField HeaderText="Name" SortExpression="Name">
     <EditItemTemplate>
     <asp:TextBox ID="txtName" runat="server" 
                  Text='<%# Bind("Name") %>'>
     </asp:TextBox>
     </EditItemTemplate>
     <ItemTemplate>
     <asp:Label ID="lblName" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("Name") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     
     <asp:TemplateField HeaderText="Locaton" 
                        SortExpression="Location">
     <EditItemTemplate>
     <asp:TextBox ID="txtLocation" runat="server" 
                  Text='<%# Bind("Location") %>'>
     </asp:TextBox>
     </EditItemTemplate>
     <ItemTemplate>
     <asp:Label ID="lblLocation" runat="server" BackColor="AliceBlue" 
                Text='<%# Eval("Location") %>'>
     </asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     </Columns>
</asp:GridView>
     
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
     InsertMethod="Insert" 
     OldValuesParameterFormatString="original_{0}" 
     
     SelectMethod="GetData" 
          TypeName="DataSet1TableAdapters.DetailsTableAdapter" 
     UpdateMethod="UpdateQuery">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Location" Type="String" />
                <asp:Parameter Name="ID" Type="Decimal" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="ID" Type="Decimal" />
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Location" Type="String" />
            </InsertParameters>
        </asp:ObjectDataSource>
    </div>

Save,build and run the application

Hope this helps

Download sample code attached



Related posts:
Insert Edit Delete record in GridView using SqlDataSource

ASP.NET Edit or update multiple records/rows in gridview with checkbox

Delete multiple rows records in Gridview with checkbox and confirmation

Continue Reading...

Saturday, June 6, 2009

15

Send Email using Gmail ASP.NET C# VB.NET

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

you need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)
{
  MailMessage mail = new MailMessage();
  mail.To.Add("jainamit.agra@gmail.com");
  mail.To.Add("amit_jain_online@yahoo.com");
  mail.From = new MailAddress("jainamit.agra@gmail.com");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com";
  smtp.Credentials = new System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword");
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail
 
Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage() 
  mail.To.Add("jainamit.agra@gmail.com")
  mail.To.Add("amit_jain_online@yahoo.com")
  mail.From = New MailAddress("jainamit.agra@gmail.com")
  mail.Subject = "Email using Gmail"
 
  String Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET"
  mail.Body = Body
 
  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient() 
  smtp.Host = "smtp.gmail.com"
  smtp.Credentials = New System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub


Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

Hope this helps


Continue Reading...

Friday, June 5, 2009

0

Trace mobile phone number in india

Use the link mentioned below to trace mobile phone number in india.
You can also track operator name and Circle of mobile number.


Click this link to trace mobile number in India

Enter 10 digits mobile number in the search box and click on Trace


Have fun



Related posts:
Track Mobile Phone number location and operator in India

Continue Reading...

Saturday, May 30, 2009

1

Unable to debug The binding handle is invalid VS2005

If you are trying to debug in Visual Studio 2005 and and not able to use breakpoints and getting unable to debug - the binding handle is invalid error in VS 2005 than follow these steps to fix this error.


Go control panel of your windows OS

Double click on Administrative tools > services

Now in services window > look for Terminal Services

Right click on it ans select properties > check it's startup type > it might be disabled

Restart the service and change startup type to Automatic

This should fix your problem

Continue Reading...

Friday, May 22, 2009

4

ASP.NET Add AutoNumber Column in GridView or DataList

Several times we need to display Auto Number or serial number for displaying records in gridview or other similar controls in ASp.NET.

We can add AutoNumber column by using Container.DataItemIndex property in html markup of the Gridview.



Here's the sample html markup for the page

<title>Auto Number Cloumn in GridView </title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" AutoGenerateColumns="False"
              DataSourceID="SqlDataSource1" PageSize="6" 
              AlternatingRowStyle-BackColor="#006699" 
              AlternatingRowStyle-ForeColor="#FFFFFF" >
    <Columns>
    <asp:TemplateField HeaderText="Serial Number">
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Name" HeaderText="Name" 
                    SortExpression="Name" />
    <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
    </Columns>
    </asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Hope this helps

Continue Reading...

.NET Resources

Further Readings

Find More Articles


Followers

Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

Follow me on Twitter

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer


C#.NET Articles and tutorials,ASP.NET Articles - blog by amiT jaiN