Wednesday, September 1, 2010

Free Download Software

Adobe acrobat reader (http://okular.kde.org/download.phd)
Adobe pagemaker Scribus(http://www.scribus.net/)
Adobe photoshop CinePaint (http://www.cinepaint.org/)
Dream Weaver KompoZer (http://www.kompozer.org)
Fhontografer FontForge (http://fontforge.sourceforge.net/)
Microsoft FrontPage Quanta Plus (http://quanta.kdewebdev.org/)
Microsoft Office OpenOffice (http://openoffice.org/)
Microsoft outlook Express Thunderbird (http://www.mozillamessaging.com/enUS/thunderbird/)
Microsoft Project kplato (http://koffice.org/kplato/)
MSN Messenger Pidgin (http://pidgin.im)
Nero Burning Rom X-CD-Roast (http://www.xcdroast.org/)
Winamp auidence (http://audacious-media-player.org/Main_Page)
Window Media player KPlayer (http://kplayer.sourceforge.net/)
VLC Player (http://www.videolan.org/vlc/)
Winzip (http://www.7-zip.org)

General HR questions

1. Tell about yourself and job
2. Tell about current project
3. What are sequence diagrams, collaboration diagrams and difference between them
4. What is your role in the current project and what kinds of responsibilites you are handling
5. What is the team size and how do you ensure quality of code
6. What is the S/W model used in the project. What are the optimization techniques used. Give examples.
7. What are the SDLC phases you have invloved
8. About educational background
9. About work experience
10. About area of work
11. Current salary, why are looking for a change and about notice period About company strength, verticals, clients, domains etc.
12. Rate yourself in different areas of .NET and SQL
13. About procsses followed
14. Notice period
15. Appraisal process
16. About effort estimation
17. Whether salary negotiable
18. Why are looking for a change
19. How fo you appraise a person
20. Do you think CMM process takes time
21. About peer reviews
22. About educational background, work experience, and area of work

Thanks & Regards
Santosh

Project related questions

1.Tell about your current project
2. Tell about your role
3. What is the toughest situation you faced in the development
4. How often you communicate with the client
5. For what purposes, you communicate with the client
6. What is the process followed
7. Explain complete process followed for the development
8. What is the life cycle model used for the development
9. How do communicate with team members
10. How do you say you are having excellent team management skills
11. If your client gives a change and asks for early delivery. How will you manage.
12.How will gather requirements and where do you record. Is it in word / Excel or do you have any tool for that
13. What is the stage when code is delivered to the client and he is testing it.
14. What are the different phases of SDLC
15. How do you handle change requests
16. How do you perform impact analysis
17. How do you write unit test cases.
18. About current project architecture

Thanks & Regards
Santosh

The IListSource does not contain any data sources

Sol:parameter mismatch does not match from stored procedure which you passing from .net.

How to handle OnActiveTabChanged event of AJAX Tab control

This Articles explian how to handle ActiveTabChanged Event of AJAX TabControl in asp.net.

ActiveTabIndex="0" BorderStyle="None" Width="742px" BorderWidth="0" OnActiveTabChanged="tbcRatingMaster_ActiveTabChanged"
AutoPostBack="True">


protected void tbcRatingMaster_ActiveTabChanged(object sender, EventArgs e)
{
if (tbcRatingMaster.ActiveTabIndex == 0)
{
//AddGrpBind();
btnSaveRG.Text = "Save";
txtGroup.Text = "";
txtGroup.Text = "";
}
if (tbcRatingMaster.ActiveTabIndex == 1)
{
txtItem.Text = "";
}
if (tbcRatingMaster.ActiveTabIndex == 2)
{
rbtnType.SelectedValue = "P";
gvRating.Visible = false;
txtItem.Text = "";
txtGroup.Text = "";
}
}

Thanks & Regards
Santosh Singh

Page Life Cycle of an ASP.NET

The life cycle starts when a user requests a web page through his/her browser. The Web server than process the page through a sequence of steps before response is sent back to the user's browser. The steps are as:

1. Page Request
2. Start
3. Page Initialization
4. Load
5. Validation
6. PostBack Event Handling
7. Render
8. Unload

Page Request
The page request occurs before the page life cycle begins. When a user requests the page, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page Initialization
During page initialization, controls on the page are available and each control's UniqueID are generated but not their properties. Any themes are also applied to the page.

Developers have access to the Init, InitComplete and PreLoad methods in this stage. The methods are as follows:

* Init: This event is raised after all controls have been initialized and any skin settings have been applied. This event is used to read or initialize control properties.
* InitComplete: The Page object raises this event. This event is used for processing tasks that require completion of all initialization.
* PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. The OnLoad event method is fired during this stage.
This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

PostBack Event Handling
If the request is a postback, any event handlers are called. The event handling for server controls occurs during this stage.

Render
During rendering, view state is saved to the page and then the page calls on each control to contribute its rendered output to the OutputStream of the page's Response property. Render is not really an event. The HTML of the page and all controls are sent to the browser for rendering.

Unload
Unload is called when the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed. The cleanup includes routines such as closing database connections and file streams, or, event logging and other tasks.

Conclusion
When a Web page is requested, the server creates objects associated with the page and all of its child controls objects and uses these to render the page to the browser. Once the final stage is complete, the web server destroys these objects, to free up resource to handle additional request.

Insert record in database using stored procedure in asp.net

In this article am explaining very simpe thing insert record in database using stored procedure,that will very help full for entry level programmer.

web.config
 <connectionStrings>  
<add name="conString" connectionString="Data Source=.\SQLEXPRESS; database=Northwind;Integrated Security=true"/>:
</connectionStrings>


Used Stored procedure
CREATE PROCEDURE [dbo].[AddUser]
(
@FName varchar(50),
@LName varchar(50),
@DateOfBirth datetime,
@City varchar(50),
@State varchar(50)
)
AS
BEGIN

SET NOCOUNT ON;
INSERT INTO UserDetails (FName, LName, DateOfBirth, City, State)
VALUES (@FName, @LName, @DateOfBirth, @City, @State)
END


C# code

 String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;  
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddUser";
cmd.Parameters.Add("@FName",SqlDbType.VarChar).Value = txtFName.Text.Trim();
cmd.Parameters.Add("@LName", SqlDbType.VarChar).Value = txtLName.Text.Trim();
cmd.Parameters.Add("@DateOfBirth", SqlDbType.DateTime).Value = txtDOB.Text.Trim();
cmd.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("@State", SqlDbType.VarChar).Value = txtState.Text.Trim();
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}

Tuesday, August 31, 2010

Website Deployment

Internet Information Services is used to make your computer a web server. If we want to have a web server for developing dynamic website or want to publish
website on our own server then we install the IIS.Internet Information Server (IIS) is a World Wide Web server, a Gopher server and an FTP server all rolled
into one. IIS means that you can publish WWW pages.
If you want to your web application accessible to any other pc in intranet or internet you need to IIS.

Below are steps for deployment:
1.Right click your website and click on Publish website.All compiles files are ready for deployment.
2.Create a backup for database whichever you are using and restore it on production server.
3.Go to server using ftp or filezila copy all compiles file on server.
4.Open Webconfig and change the connection string according to your Database name and server.
5.Create a virtual directory for this website.
6.Your website is ready.
7.Test website http://192.163.0.234(ServerName)/VDName/Login.aspx

Thanks & Regards
Santosh

Difference Between .net framework 2.0,3.0 and 3.5

NET framework 2.0:

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework


.NET framework 3.0:

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website


.NET framework 3.5:

It implement Linq evolution in language. So we have the folowing evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.

Sunday, August 29, 2010

String Manupulation

i have a string like "a,b,c. upto n values"..
Show this string like
a,
b,
C

Sol
string str = "a,b,c";
string[] arr = str.Split(',');
foreach (string s in arr)
{
Response.Write(s + ",
");
}

Saturday, August 28, 2010

GridView Edit:on clicking edit a new page should be open where user can update data

 GridView Edit:on clicking edit a new page should be open where user can update data  
 On clicking edit in GridView a new page should be open where user can update data. In this article i am explaining how to update record using GridView.When User Click edit button in GridView new page will be open where user can update record.in second page i have just find the data not wrriten the code for update.  
 Here also i have written code for delete record in GridView and if GridView has no record show message no record found.  
 First Page code  
 public void GridViewBind()  
 {  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           DataSet ds = SqlHelper.ExecuteDataset(conn, "LeaveMaster_Select");  
           GridView1.DataSource = ds.Tables[0];  
           GridView1.DataBind();  
      }  
 }  
 protected void ImgDelete_Click(object sender, ImageClickEventArgs e)  
 {  
      ImageButton img = (ImageButton)sender;  
      Label Leave = img.FindControl("Label1") as Label;  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           conn.Open();  
           using (SqlTransaction t = conn.BeginTransaction())  
           {  
                try  
                {  
                     exceptionMessage.Text = SqlHelper.ExecuteScalar(t, "LeaveMaster_Delete", Leave.Text, "", 'D').ToString();  
                     t.Commit();   
                     GridViewBind();  
                }  
                catch  
                {  
                     t.Rollback();  
                }  
           }  
           conn.Close();  
      }  
 }   
 protected void ImgbtnDetails_Click(object sender, ImageClickEventArgs e)  
 {  
      //Selecting a Record from Grid For Updation..  
      ImageButton aspSender = sender as ImageButton;  
      Label lblId = aspSender.FindControl("lblLeaveID") as Label;  
      Response.Redirect("~/LeaveDetails.aspx?Id=" + lblId.Text + "");   
 }  
 ===========  
 2nd page  
 if (Request.QueryString["Id"] != null)  
 {  
      Id = Convert.ToInt32(Request.QueryString["Id"].ToString());  
      string str = "SELECT LeaveCode, LeaveDesc, LeaveId FROM LeaveMaster WHERE (LeaveId = "+Id+")";  
      DataTable dt1 = SqlHelper.ExecuteDataset(conStr, CommandType.Text, str).Tables[0];  
      txtCode.Text = dt1.Rows[0]["LeaveCode"].ToString();  
      txtCode.Enabled = false;  
      txtShortName.Text = dt1.Rows[0]["LeaveDesc"].ToString();  
      txtShortName.Enabled = false;   
 }  
 aspx Page  
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="LeaveId" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"   
 Width="700px" PageSize="10" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" >  
      <Columns>  
           <asp:TemplateField HeaderText="LeaveId" InsertVisible="False" SortExpression="LeaveId" Visible="False">  
                <EditItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("LeaveId") %>'></asp:Label>  
                </EditItemTemplate>  
                <ItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("LeaveId") %>'></asp:Label>  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:BoundField DataField="LeaveCode" HeaderText="Leave Code" SortExpression="LeaveCode" />  
           <asp:BoundField DataField="LeaveShortDesc" HeaderText="Short Desc" SortExpression="LeaveShortDesc" />  
           <asp:BoundField DataField="LeaveLongDesc" HeaderText="Long Desc" SortExpression="LeaveLongDesc" />  
           <asp:CommandField ButtonType="Image" HeaderText="Edit" SelectImageUrl="~/Image/img_edit.png" ShowSelectButton="True">  
           <ItemStyle HorizontalAlign="Center" />  
           </asp:CommandField>  
           <asp:TemplateField HeaderText="Details">  
                <EditItemTemplate>  
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                </EditItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="40px" />  
                <ItemTemplate>  
                <asp:ImageButton ID="ImgbtnDetails" runat="server"   
                OnClick="ImgbtnDetails_Click" />  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="Delete">  
                <ItemTemplate>  
                <asp:ImageButton ID="imgbtnDelete" runat="server"   
                OnClick="ImgDelete_Click" OnClientClick="return ConfirmDelete();" />  
                </ItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="50px" />  
           </asp:TemplateField>  
      </Columns>  
      <EmptyDataTemplate>No record found !</EmptyDataTemplate>  
 </asp:GridView>  

Friday, August 27, 2010

Send mail using asp.net c# code

Send mail using asp.net c# code
This code describe how to send mail where mail id is stored in database and mail sender detail From,To,are stored in web.config file.Mail body can be customized according to requirement as described in code.

 public void MailSend()  
{
try
{
string mailToAdd = String.Empty;
MailMessage message1 = new MailMessage();
string strMail;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["SqlConnString"]);
SqlDataReader dr;
conn.Open();
SqlCommand cmd = new SqlCommand("usp_MediaRegistration", conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
strMail = (string)dr["emailID"];
message1.IsBodyHtml = true;
string MailFrom = ConfigurationManager.AppSettings["from"].ToString();
message1.From = new MailAddress(MailFrom);
message1.To.Add(new MailAddress(strMail).ToString());
message1.Subject = "Headline of the press release";
if (Request.QueryString["strmail"] == "0")
{
message1.Body = "<html><body><table><tr><td>Dear Users,</td></tr><br/>" +
"<tr><td><t/>This is to inform you that ...your message. <br/>" +
"<tr><td><t/>Please click on the link to see details....: <br/>" +
"<tr><td><a href='" + "http://xyz.com/mediapage.aspx?year=" + drlMyyyy.SelectedItem.Value
+ "'>" + "http://xyz.com/mediapage.aspx?year=" + drddMyyyy.SelectedItem.Value +
"</a></td></tr><br/>" +
"<tr><td>Thanks & Reagrds,</td></tr>" +
"<tr><td>santosh singh</td></tr> </table></body></html>";
}
}
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpHost"]);
client.Send(message1);
}
catch (Exception ex)
{
string str1 = string.Format("Message Sending Fail Due To {0}.", ex.Message);
}
}


Thanks & Regards
Santosh Singh

Wednesday, August 25, 2010

Resize image in ASP.NET

In this example i am going to describe how to resize image in ASP.NET before/and upload to ms sql database using C# and Vb.NET.

For this i am using FileUpload control to upload the image in datbase after resizing.
I am also displaying the Image in Gridviw after uploading to database.

 public partial class _Default : System.Web.UI.Page   
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strImageName = txtName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
string strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
{
// Resize Image Before Uploading to DataBase
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 240;
int maxWidth = 320;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
UploadedImage.Value = image;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
GridView1.DataBind();
}
}
}
}


aspx code
 <form id="form1" runat="server">  
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
<asp:Label ID="lblMessage" runat="server"</asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [Images]">
</asp:SqlDataSource>
</form>


Thanks & Regards
Santosh

Tuesday, August 24, 2010

ViewState And Session example

Hi,

View state is used for store data at page level,you cant access View state data to another page.
Session state is used for store data and you can access anywhere in your website.
Session state is state specific information per client basis.

Example is given below.

View State:
 protected void btnSubmit_Click(object sender, EventArgs e)  
{
ViewState["DataScorceName"] = datasource;
ViewState["ClientName"] = txtCustomer.Text;
}
//Retrieve viewstate information
txtCname.Text = ViewState["ClientName"]
Store information in Session State:
Session["EmpName"] = txtUser.Text;
//Retrieve session value in 2nd page
lblEmp.Text = Session["UserName"].ToString();


Thanks & Regards
Santosh Singh

How to create connection string dynamically

Here i am using viewstate to create connection string at run time.
 protected void btnSubmit_Click(object sender, EventArgs e)  
{
ViewState["DataScorceName"] = datasource;
ViewState["Customer"] = txtCustomer.Text;
}
public void MyFunction()
{
string sqlConnectionString = "Persist Security Info=True;User ID=sa;Password=Sa;Initial Catalog=" + DBName + ";Data Source='" + ViewState["DataScorceName"] + "'";
}

How to reverse a string

 char [] myArray = txtName.Text.ToCharArray();  
Array.Reverse( myArray );
string strReversed = new string( myArray );
lblName.Text = strReversed;

how to use Sql server Function

Sql server Function With Arguments

here it is simple example how to use function n sql server.
1.Create function
2.use this function where required.

CREATE FUNCTION AddTwoNumber(@Num1 Decimal(6,2),
@Num2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Num1 + @Num2
RETURN @Result
END;
GO


PRINT MyDbName.dbo.AddTwoNumber(100, 200);

Sp for Creating db

Stored procedure for creating database.
When you want to create database at run time using c# .net here is stored procedure execute this and pass database name as parameter.

Create proc [dbo].[usp_Database]
(
@dbName varchar(50)
)
as

IF NOT EXISTS (SELECT 'True' FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME = @dbName)
-- DROP DATABASE ' + @dbName + '

DECLARE @device_directory NVARCHAR(520)
SELECT @device_directory = SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1)
FROM sys.database_files
WHERE (name = N'master')

EXECUTE (N'CREATE DATABASE ' + @dbName + '
ON
(NAME = ' + @dbName + ',
FILENAME = ''' + @device_directory + '' + @dbName + '.mdf'',
SIZE = 50MB,
MAXSIZE = 125MB,
FILEGROWTH = 10MB)
LOG ON
(NAME = ''NorthwindBulkLog'',
FILENAME = ''' + @device_directory + '' + @dbName + '.ldf'',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB)')

SetFocus to TextBox in GridView control

How to set focus in a GridView

Set Focus to TextBox in GridView when click on Edit Some time we have requirement to set focus in gridview,so here i am describing to how to this.
Drag and drop a gridview and bind it according to below code.

 protected void GridViewBind()  
{
try
{
Ds = obBLLclass.GetData();
if (Ds.Tables[0].Rows.Count > 0)
{
gridview.DataSource = Ds;
gridview.DataBind();
}
}
catch (Exception ex)
{
Message.Text = ex.Message;
}
}
protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
gridview.EditIndex = e.NewEditIndex;
GridViewBind();
gridview.Rows[e.NewEditIndex].FindControl("txtname").Focus();
}
protected void gridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridview.PageIndex = e.NewPageIndex;
GridViewBind();
}


Thanks & Regards
Santosh Singh

How to insert excel file into sql database in ASP.NET

Import EXCEL sheet data to SQL Database table in ASP.NET
Here I will explain how to read excel file data and insert into in sql server database.

 protected void btnupload_Click(object sender, EventArgs e)   
{
String excelConnectionString1;
String fname = sendupload.PostedFile.FileName;
if (sendupload.PostedFile.FileName.EndsWith(".xls"))
{
String excelsheet;
sendupload.SaveAs(Server.MapPath("~/Image/" + sendupload.FileName));
if (sendupload.PostedFile.FileName.EndsWith(".xls"))
{
excelConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/ExcelFiles/" + sendupload.FileName) + ";Extended Properties=Excel 8.0";
OleDbConnection myEcelConnection1 = new OleDbConnection(excelConnectionString1);
myEcelConnection1.Open();
if (txtsheet.Text.Length == 0)
{
lblmsg.Text = "Please Write File Name";
}
else
{
excelsheet = "[" + txtsheet.Text + "$" + "]";
string sheet = "Select * from [" + txtsheet.Text + "$" + "]";
OleDbCommand cmd1 = new OleDbCommand(sheet, myEcelConnection1);
cmd1.CommandType = CommandType.Text;
OleDbDataAdapter myAdapter1 = new OleDbDataAdapter(cmd1);
DataSet myDataSet1 = new DataSet();
myAdapter1.Fill(myDataSet1);
int a = myDataSet1.Tables[0].Rows.Count - 1;
string name;
string id;
string cls;
string num;
for (int i = 0; i <= a; i++)
{
name = myDataSet1.Tables[0].Rows[i].ItemArray[0].ToString();
id = myDataSet1.Tables[0].Rows[i].ItemArray[1].ToString();
cls = myDataSet1.Tables[0].Rows[i].ItemArray[2].ToString();
num = myDataSet1.Tables[0].Rows[i].ItemArray[3].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand command = new SqlCommand("Insert into StudentDetails(StudentName,CivilIdNumber,Class,StudentID)values(@valname,@valids,@valcls,@valnum)", con);
command.Parameters.Add("@valname", SqlDbType.VarChar, 50).Value = name;
command.Parameters.Add("@valids", SqlDbType.VarChar, 50).Value = id;
command.Parameters.Add("@valcls", SqlDbType.VarChar, 50).Value = cls;
command.Parameters.Add("@valnum", SqlDbType.VarChar, 50).Value = num;
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
}
}
}
}

.aspx page
 <table width="100%">   
<tr>
<td colspan="3"> <span style="font-family: Segoe UI"> File Upload</span> </td>
</tr>
<tr>
<td colspan="3">
<asp:FileUpload ID="sendupload" runat="server" /> </td>
</tr>
<tr>
<td colspan="3">
<span style="font-family: Segoe UI"> Sheet Name: </span>
<asp:TextBox ID="txtsheet" runat="server"> </asp:TextBox>
<asp:Label ID="lblmsg" runat="server"> </asp:Label>
</td>
</tr>
<tr>
<td> <asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" /> </td>
</tr>
</table>


Thanks & Regards
Santosh