3

Images In Gridview DataList Using ObjectDataSource

In this example i am explaining how to Add or Show Images in GridView or DataList using ObjectDataSource In Asp.Net C# VB.NET. 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.

Images In Gridview DataList Using ObjectDataSource


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

20

Read Write Edit Word Document In ASP.NET

In this article i am explaining how to Read Write Edit Word Document With FileStream StreamWriter In ASP.NET. 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.

Read Write Edit Word Document In ASP.NET


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 and stringBuilder we need to add these namespace
using System.IO;
using System.Text;

C# code behind
protected void Button1_Click(object sender, EventArgs e)
{
    //Create stringBuilder to write formatted 
    //Text to word file
 StringBuilder strBuilder = new StringBuilder();
 strBuilder.Append("<h1 title='Header' align='Center'>
     Writing To Word Using ASP.NET</h1> ".ToString());

 strBuilder.Append("<br>".ToString());
 strBuilder.Append("<table align='Center'>".ToString());
 strBuilder.Append("<tr>".ToString());

 strBuilder.Append("<td style='width:100px;color:green'>
                          <b>amiT</b></td>".ToString());

 strBuilder.Append("<td style='width:100px;color:red'>
                              India</td>".ToString());
 strBuilder.Append("</tr>".ToString());
 strBuilder.Append("</table>".ToString());

 string strPath = Request.PhysicalApplicationPath
                         + "\\document\\Test.doc";

 //string strTextToWrite = TextBox1.Text;
 FileStream fStream = File.Create(strPath);
 fStream.Close();
 StreamWriter sWriter = new StreamWriter(strPath);
 Writer.Write(strBuilder);
 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();
Response.Write(TextBox2.Text);
}

VB.NET code
Protected Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
Dim strBuilder As New StringBuilder()
strBuilder.Append("<h1 title='Header' align='Center'>
     Writing To Word Using ASP.NET</h1> ".ToString())
strBuilder.Append("<br>".ToString())
strBuilder.Append("<table align='Center'>".ToString())
strBuilder.Append("<tr>".ToString())

strBuilder.Append("<td style='width:100px;color:green'>
                           <b>amiT</b></td>".ToString())
strBuilder.Append("<td style='width:100px;color:red'>
                               India</td>".ToString())
strBuilder.Append("</tr>".ToString())
strBuilder.Append("</table>".ToString())
'string path = @"C:\Test.doc";

Dim strPath As String = 
Request.PhysicalApplicationPath & "\document\Test.doc"
    
'string strTextToWrite = TextBox1.Text;
Dim fStream As FileStream = File.Create(strPath)
fStream.Close()
Dim sWriter As New StreamWriter(strPath)
sWriter.Write(strBuilder)
      
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()
Response.Write(TextBox2.Text)
End Sub

hope this helps

Download the sample code attached


40

ASP.NET Custom MemberShip Provider Database

Here i'm explaining how to Create And Use Custom MemberShip Provider Database in ASP.NET 2.0,3.5.4.0. If you want to use Custom or your own DataBase as membership Provider instead of ASPNETDB.MDF database provided by asp.net membership provider class, 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

Create Custom MemberShip Provider Database in ASP.NET
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
Use Custom MemberShip Provider Database in ASP.NET 
 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 

9

GridView With ObjectDataSource Example Insert Edit Update

In this example i am explaining how to Insert Edit Update GridView With ObjectDataSource In Asp.Net 2.0,3.5,4.0. 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

54

Send Email Using Gmail Or SMTP 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

Continue reading here


56

Trace Mobile Number In India

Trace Mobile Number In India With Circle Operator Name and Location.

Enter phone number in textbox and Use the trace button below to trace mobile phone number in india.

You can also track operator name and Circle of mobile number.


Enter mobile number in the textbox and click on Trace button.

Enter 10 digits mobile phone number to trace:


Have fun


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

Find More Articles