Hi priyatrip,
I have created a sample that full-fill your requirement. You have to write the code on page load of home page for inserting the record to the database when user visit the websides home page. and on button click show the gridview like i have done below.
SQL
CREATE TABLE VisitorHistory(ID INT IDENTITY PRIMARY KEY,IPADDRESS VARCHAR(50),NAME VARCHAR(100),DATE DATETIME)
HTML
<asp:GridView ID="gvHistory" runat="server" AutoGenerateColumns="false" EmptyDataText="No history found."
Visible="false">
<Columns>
<asp:BoundField DataField="NAME" HeaderText="Name" />
<asp:BoundField DataField="DATE" HeaderText="Date" DataFormatString="{0:dd/MM/yyyy}"/>
<asp:BoundField DataField="DATE" HeaderText="Time" DataFormatString="{0:HH:mm:ss}"/>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnHistory" Text="View History" runat="server" OnClick="ViewHistory" />
Code
string str = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ipAddress = string.Empty;
string visitorName = string.Empty;
string dateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
visitorName = hostEntry.HostName;
if (ipAddress == string.Empty || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
visitorName = HttpContext.Current.Request.ServerVariables["REMOTE_USER"];
}
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO VisitorHistory VALUES (@ipAddress,@Name,@DateTime)", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ipAddress", ipAddress);
cmd.Parameters.AddWithValue("@Name", visitorName);
cmd.Parameters.AddWithValue("@DateTime", dateTime);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
private void PopulateVisitorHistory()
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 IPADDRESS,MAX(NAME) NAME,MAX(DATE)DATE FROM VisitorHistory GROUP BY IPADDRESS", con))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvHistory.DataSource = ds;
gvHistory.DataBind();
}
}
}
protected void ViewHistory(object sender, EventArgs e)
{
gvHistory.Visible = true;
this.PopulateVisitorHistory();
}
Screenshot
