Showing posts with label c sharp. Show all posts
Showing posts with label c sharp. Show all posts

Thursday, May 10, 2012

How to dynamically add CSS file in ASP.NET

Here i will show how to add css file to page in code behind.For this i have created a custom HTML link control and assign the styles sheet URL ,set remaining properties. We can see one more thing here is creating HTML control dynamically
In aspx page:
<link href="~/styles.css" rel="Stylesheet" type="text/css" />
Codebehind:

       HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", "~/Styles.css");
this.Header.Controls.Add(link);
This.Header is used to add the link to aspx page

Wednesday, May 9, 2012

Convert a Generic List into a Datatable in asp.net

According to my application requirement ,i need to bind the data to data table from List in asp.net using C#.net.For this i just create table dynamically then bind the data using loop iteration on list.
In the below we can see two methods which are CreateDataTable which is used to create a data table and AddDataToTable which is used to bind the data .
public DataTable converttoTable(List<string> list, string tableName)
{
DataTable table;
table = CreateDataTable(); 
if (list.Count > 0)
{
foreach (string item in list)
{
AddDataToTable(item, table);
}
}
return table;
}
This function will execute when the items are added to data table.
private void AddDataToTable(string rowItem, DataTable myTable)
{
try
{
DataRow row;
row = myTable.NewRow();
string[] itemStringArray = SplitByString(rowItem, "[]");
row["Iame"] = itemStringArray[0];
row["Id"] = itemStringArray[1];
row["Address"] = itemStringArray[2] == "" ? "0" : itemStringArray[2];
row["Year"] = itemStringArray[3];
row["salary"] = itemStringArray[4];
myTable.Rows.Add(row);
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
//create a table dynamically
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Name";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Id";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Address";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Year";
myDataTable.Columns.Add(myDataColumn);           

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Salary";
myDataTable.Columns.Add(myDataColumn);

return myDataTable;
}

Monday, April 9, 2012

how to read data from excel file in asp.net

Here will how to read the data from excel and export record information to label.For this i will use data reader which id used to read and forward the data .We can not do the manipulations the data while passing from excel to data reader Asp.net:
using System.Data.OLEDB;
//pageload
OleDbConnection cn=new OleDbConnection("provider=microsoft.jet.oledb.4.0;datasource=e:\\asp.net12\\inventorymdb");
OleDb Command cmd=New OleDb Command("select *from product",cn);
OleDbDataReader dr;
cn.Open():
dr=cmd.ExcuteReader();
while(dr.Read)
{
//arrabge record info into label
lblproductinfo.Text=dr["proid"].ToString()+" "+dr["proname"].ToString();
}
vb:
Dim cn As New OleDbConnection("provider=microsoft.jet.oledb.4.0;datasource=e:\asp.net12\inventorymdb")
Dim cmd As New OleDbCommand("select *from product",cn")
Dim dr As New OleDbDataReader
cn.Open()
dr = cmd.ExcuteReader()
While dr.Read
 'arrabge record info into label
 lblproductinfo.Text = dr("proid").ToString() & " " & dr("proname").ToString()
End While

Wednesday, April 4, 2012

Type casting with c#.net

Recently i have seen one Query about c to c# data type convert.Type concept is a concept of converting one data type to another data type.C#.net supports two types of typecasting. Implicit Typecasting:It will be done under control of CLR and convert from lower to higher ex:
byte x=10;
int i=x;
byte-->int
Explicit Type Casting:It will be done undercontrol of programmer and convert data type from high to lower
int i=10;
byte x=i;
int-->byte
obs:
long-->Int:-Explicit
float-->double:-Implicit
Int-->Float:-implicit
Float-->Int:-Explicit
C#.Net supports 4 types of methodologies for explicit type casting 1.c++ style of casting 2.Converting 3.Parsing

Friday, March 9, 2012

how to send a mail with attachment in asp.net

In previous articles we have seen how to send a mail in asp.net,send HTML formated mail.In this post i will show how to send mail with attachment.Here the local file  which in root directory of the application has been used as attachment for mail.This scenario will be place when we send error log files to our mail.
Note:place code in Button click event which has to be used for send mail functionality
path_profile = AppDomain.CurrentDomain.BaseDirectory;
path_profile = path_profile + @"Log\Adminmailfile.txt";

string ServerName = ConfigurationManager.AppSettings["smtpservername"].ToString();
string FromAddress = ConfigurationManager.AppSettings["fromaddress"].ToString();
string adminmail = ConfigurationManager.AppSettings["AdminMail"].ToString();
string User = ConfigurationManager.AppSettings["user"].ToString();
string PWD = ConfigurationManager.AppSettings["PWD"].ToString();
DataSet dsmonthname = clsdb.getmonthname(cmonth);
//send message
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(ServerName);
mail.From = new MailAddress(FromAddress);
mail.To.Add(adminmail);
mail.Subject = "Alert" + System.DateTime.Now;
mail.Body = "Alert" + System.DateTime.Now;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(path_profile);
mail.Attachments.Add(attachment);
SmtpServer.Credentials = new System.Net.NetworkCredential(User, PWD);
SmtpServer.Send(mail);
Vb:
path_profile = AppDomain.CurrentDomain.BaseDirectory
path_profile = path_profile & "Log\Adminmailfile.txt"

Dim ServerName As String = ConfigurationManager.AppSettings("smtpservername").ToString()
Dim FromAddress As String = ConfigurationManager.AppSettings("fromaddress").ToString()
Dim adminmail As String = ConfigurationManager.AppSettings("AdminMail").ToString()
Dim User As String = ConfigurationManager.AppSettings("user").ToString()
Dim PWD As String = ConfigurationManager.AppSettings("PWD").ToString()
Dim dsmonthname As DataSet = clsdb.getmonthname(cmonth)
'send message
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient(ServerName)
mail.From = New MailAddress(FromAddress)
mail.[To].Add(adminmail)
mail.Subject = "Alert" & System.DateTime.Now
mail.Body = "Alert" & System.DateTime.Now
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(path_profile)
mail.Attachments.Add(attachment)
SmtpServer.Credentials = New System.Net.NetworkCredential(User, PWD)
SmtpServer.Send(mail)

Tuesday, February 14, 2012

Convert string array to list in c#

Title:How to Convert string array to generic list in asp.net using c#.net

Description:
As in previous articles we have seen the data type conversions.Now i would like to give an example on how to convert the string array to List .To elaborate the example i have used a string "strs".Then it will split and store into array "StrArray".Finally the array is convert to list using below peace code and assign to list details List.
C#:
string strs = "1,1,3,4";
List detailsList;
string[] StrArray = strs.Split(',');
int[] intArray = Array.ConvertAll(strArray, new Converter(Convert.ToInt32));
detailsList = intArray.ToList();
VB:
Dim strs As String = "1,1,3,4"
Dim detailsList As List
Dim StrArray__1 As String() = strs.Split(","C)
Dim intArray As Integer() = Array.ConvertAll(strArray, New Converter(Convert.ToInt32))
detailsList = intArray.ToList()

Wednesday, February 8, 2012

how to Passing a server side variable into javascript

Recently I have seen a server side code which is used to pass the server side value to javascript.So whenever we will transfer the server side value to Javascript we don't need to write server side .For this here i will show a simple way to pass the variable to javascript from server side
<input id="hidCtrl" type="hidden"  runat="server" value='<%# ServerVaribaleValue %>'/>
Here the server side value which is"ServerVaribaleValue" is assigned as a hidden field value.The below javascript will get the value of hidden field
<script language="javascript">
function onclick(){
alert(document.getElementById('hidctrl').value);
}
</script>

Sunday, February 5, 2012

Export excel data to sql server Data base in asp.net

Now a days we have an mandatory requirements like export data to excel in asp.net and excel to database etc.Here i will show how to export the data from excel to Database in asp.net.In the below example i have taken one excel sheet"testexcel.xls" with data.when ever work with excel data base we have to add one namespace i;e, System.Data.OleDb;.
DataTable dt = new DataTable(); 
OleDbConnection oledbcn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath("~/testexcel.xls").ToString() + ";
Extended Properties=Excel 8.0;");  
//sheet name 
string SheetName="orders";oledbcn.Open(); 
OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [" + SheetName + "$]", oledbcn);  
OleDbDataAdapter oledbad = new OleDbDataAdapter();  
oledbda.SelectCommand = cmd;
oledbda.Fill(dt);   
oledbcn.Close();
//if we have a large amount of data we have to use for lop to isert the data   
StringBuilder Str =new StringBuilder();
foreach (DataRow dr in dt.Rows)
{ 
 Str.Append("INSERT INTO Orders VALUES(" + dr["ID"].ToString() + ",'" + 

dr["Name"].ToString() + "')");
}
  

Wednesday, February 1, 2012

how to use the abstract class in asp.net

The class under which we define the abstract methods is an abstract class.Abstract class has to be declared using "abstract" keyword.
abstract class example
{
public abstract void test();
}
An abstract class can contain both abstract and non abstract methods in it.Each and every abstract method which was declared under the abstract class should be given implementation with in the child class or child cannot utilize non abstract methods of the parent.An abstract class is not usable for it self because the object of an abstract class can't be created using "new" operator.It can be utilized only by the child class after giving the implementation for abstract methods of parent.If the child class doesn't provide the implementation for the abstract methods in its parent child also becomes abstract.
Example:
abstract class parent
{
public int add(int a,int b)
{
return a+b;
}
public int sud(int a,int b)
{
return a-b;
}
public abstract int mul(int a,int b);
public abstract int div(int a,int b);
}
//Add one more class child.cs

class child:parent
{
public override int mul(int a,int b)
{
return a/b;
}
public void test()
{
Console.Writeline("child method");
}
static void menu()
{
child c=new child();
Console.Writeline(c.add(2,3));
Console.Writeline(c.sub(2,3));
Console.Writeline(c.mul(2,3));
Console.Writeline(c.div(2,3));
c.Test();
console.Readline()
}
}
The object of an abstract can be created by assigning the object of it's class to it's variable,using this object every method declared and implemented under the abstract class can be called.Here the following code under the main methods of child class
Note:In derived class i have override the mul() method
parent p=new child();
Console.Writeline(p.add(2,3));
Console.Writeline(p.sub(2,3));
Console.Writeline(p.mul(2,3));
Console.Writeline(p.div(2,3));
//c.Test();//invalid
console.Readline()

Sunday, January 29, 2012

inherit control in asp.net

It is the control which id inherited from an existing control and providing additional functionalities in it.To create inherited user control the class declaration need to be as below.
ex:Masked Text box of Rich Text box which are inherited from a tex box control
public class MaskedTextBox :TextBox 
public class RichTextBox:TextBox 
Creating a mytextbox control which can be customised in such a way it can accept the only numeric or characters or both numeric of characters as well anything.Open the c# control project wha we developed previously and add a new class to it naming it as mytextbox.cs and write the following code in it.

using system,windows.Forms;
namespace inherited controls
{
public class mytextbox:TextBox
{
public ENUM options{Digits,Any,Chars,char or digit};
options opt=options.Any
public myTextbox()
{
This.keypress+=new KeyPressEventHandler (myTextBox-keypress);
}
private void mytextbox_keypress(object sender,keypressevent args e)
{
if(convert.toInt32(e.keychar==8)
return;
switch(opt)
{
case option.Digits;
if(char.IsDigit(e.keychar)==false)
{
messagebox.show("enter numbers only");
e.Handled=true;
}
break;
case options.cahrs
if(char.Isletter(e.keychar)==false)
{
{
messagebox.show("enter numbers only");
e.Handled=true;
}
break;
case options.cahrs or digit
if(char.Isletter or digit(e.keychar)==false)
{
{
messagebox.show("enter numbers and chars only");
e.Handled=true;
}
break;
} 
}
public option setoption
{
get{returns opt;}
set(opt= value;}
}
}
} 
} 

Saturday, January 28, 2012

Create custom Events and Delegates with c#

when part of user controls logic and part of forms logic need to be executed at one shot ,then user defied events are required.User defined events is called  as Callback procedure.For this we have to follow four steps to develop user defined events
1.create a delegate
2.Create a event wit the help of delegate
3.raise the event (call the event)
4.Define the event (write the body)
note:When developing the control,steps 1,2,&3 need to be fallowed.While using the control step four need to be followed
Hre i will shown an example for how to create events with delagates.In my application i have created a usecontrol and it has the option to load the data in when the ocntrol is loading.For this i have created a page load event .
 Load += new EventHandler(delegate(object PreRenderSender, EventArgs Evt) { if (ViewSet.GetActiveView() != Edit)GiveOutput(); });

protected void SetOutput()
 {
 }

Friday, December 30, 2011

export gridview to excel in asp.net

Title:How to Export data from grid view to excel in c#

Description:
As per previous articles we have gone through some examples like Export grid view data to word document,Export grid view to PDF,Import excel data to Asp.net Grid view ,Export data to excel in asp.net.Here i would like to share  how to export grid view data to Excel sheet in asp.net using c#.net.It can be done in two steps.First is render to HTML from grid view then the present HTML to Excel.

Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GdvMainmasters" Runat="server" DataSourceID="OrdrDb">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID" 
SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName" 
SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address" 
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount" 
SortExpression="Amount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="OrdrDb" runat="server" 
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>" 
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
<asp:Button ID="btnexportOrderstoWord" runat="server" Text="ExportExcel" 
onclick="btnexportOrderstoWord_Click" /></div>
</asp:GridView>
<asp:Lable id="LblMsg" runat="server"/>
<asp:Button id="BtnSendtoExcel" Text="Export" runat="server" OnClick="BtnSendtoExcel_Click"/>
</div>
</form>
</body>
</html>

CodeBehind:
protected void BtnSendtoExcel_Click(object sender, EventArgs e)
{
try
{
Excelbtn = "ABC";
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",attachment;filename=OrderDetails.xls");
Response.ContentType = "application/ms-excel";
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(sw);
GdvMainmasters.AllowPaging = false;
GdvMainmasters.AutoGenerateSelectButton = false;
GdvMainmasters.Enabled = false;
GdvMainmasters.DataBind();
GdvMainmasters.HeaderRow.Cells[0].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[1].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[2].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[3].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[3].BorderStyle = BorderStyle.Inset;
for (int j = 0; j < GdvMainmasters.Rows.Count; j++)
{
GridViewRow row = GdvMainmasters.Rows[j];
GdvMainmasters.RenderControl(hwr);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
}
catch (Exception e3)
{
LblMsg.Text = e3.Message;
}
} 


Note:While run the above code we may get the some errors RegisterForEventValidation can only be called during Render.If you get an error then need to override the control.


Monday, December 26, 2011

how to write to a text file in c#

In .net we have a various classes to create, write and perform some operations on a text file which are file .Here we are using create() method to create a text file and using some classes to reading and writing text files those are TextReader,StreamReader,StreamWriter,TextWriter classes.These are abstract classes .Here i have taken a logfilepath which is the physical path of the text file.If the file is existing in path then we will write message into this text file.If the file is not existing in the path then we will create a file in this path and write a message into it
Code Behind:
public static string path = AppDomain.CurrentDomain.BaseDirectory;
public static string LogfilePath = path + @"archives\error.txt";
public static void WriteError(string msg)
 {
  try
   {
    if (!File.Exists(LogfilePath))
       {
       File.Create(LogfilePath).Close();
       }
    using (StreamWriter w = File.AppendText(LogfilePath))
       {
        w.WriteLine("\r\nLog Entry : ");
        w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture));
        string err = "Error Message:" + msg;
        w.WriteLine(err);
        w.Flush();
        w.Close();
       }
   }

Wednesday, December 21, 2011

Checkbox in grid view in asp.net||Check/Uncheck all check boxes in gridview

In previous articles i explained delete multiple rows in gridview using checkbox,Export Gridview Excel ,Export Gridview Data to PDF document,Export gridview to Word in asp.net.Grid view is providing different types of field for customization such as bound field,check box,image field,Hyperlink,Command,Template fields.Bound field is the default field for grid view.Here i will show how to use the check box inside grid view and add the value of selected row into Context.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<gridview autogeneratecolumns="False" id="gvOrdr" runat="server">
<columns>
<templatefield>
<itemtemplate>
<checkbox id="chkOrdr" runat="server"></checkbox>
</itemtemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkMainheadr"
OnCheckedChanged="chkMainheadr_OnCheckedChanged"
AutoPostBack="true" runat="server" />
</HeaderTemplate>

</templatefield>

<boundfield datafield="UserID" headertext="User ID">
<boundfield datafield="UserName" headertext="User Name">
<boundfield datafield="Role" headertext="Role">
</boundfield>

</columns>
</gridview></div></form>
</body>
</html>

Code behind:
In grid view Find Control method is provided which is access web server control with in the Template field.This return Obj type,it should be Type casted to Check Box type.So that property can be accessed.Here we will checked one check box then the value of particular row in to string using on OnCheckedChanged event
Note:We can add that string value to Text property controls like Text box,Label etc
Checked &unchecked All:
Here i have one check box in header template in aspx page.if check the header check box then all the check box should be checked .if unchecked the header check box then all the check box should be unchecked

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class CheckAllGridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}


protected void chkMainheadr_CheckedChanged(object sender, EventArgs e)
{
checkBox chkall =(CheckBox)Gvemp.HeaderRow.FindControl("chkMainheadr");
if (chkMainheadr.Checked == true)
{
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
{
CheckBox chkIndividual =(CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = true;
}
}
else
{
foreach (GridViewRow gvOrdr in gvOrdr.Rows)
{
CheckBox chkIndividual = (CheckBox)gvOrdr.FindControl("chkOrdr");
chkIndividual.Checked = false;
}
}
}
}
Get the Selected CheckBox value in Gridview:
public void chk_OnCheckedChanged(object sender, EventArgs e)
  {
    string s;
    CheckBox chsubmit=(CheckBox)Gvemp.Rows[i].FindControl("chkOrdr");
    if(chsubmit.Checked)
    s=s+gvemp.Rows[i].cells[2].Text+;

  }
//place s variable in to context
  context.items.Add("sps",s);
 

Thursday, December 15, 2011

Data Table to Data base in c#

Title:How to insert the data in to database using data table in asp.net using c#

Description:
As per example i have to insert the data from CSV file. For this task i have done two steps.One is,Bind the data to data table and then iterate the each row of data table then we can insert the data in to Data Base .Here i have checked the whether the data is empty or null in column of data table.i have shown another query in below to insert the data with out check

Code Behind:
string insertQuery = "INSERT into [Table name](Id,field2,field3,field4,field5,field6,field7,field8,field9,field10,field11) Values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},'{10}')";
foreach (DataRow dr in Datatable.Rows)
{
try
{
cmd.Connection = con;
cmd.CommandText = string.Format(insertQuery, string.IsNullOrEmpty(Convert.ToString(dr["Col1"]).Trim()) ? null : dr["Col1"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col2"]).Trim()) ? null : dr["Col2"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col3"]).Trim()) ? null : dr["Col3"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col4"]).Trim()) ? null : dr["Col4"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col5"]).Trim()) ? null : dr["Col5"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col6"]).Trim()) ? null : dr["Col6"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col7"]).Trim()) ? null : dr["Col7"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col8"]).Trim()) ? null : dr["Col8"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col9"]).Trim()) ? null : dr["Col9"].ToString().Trim(),
         string.IsNullOrEmpty(Convert.ToString(dr["Col10"]).Trim()) ? null : dr["Col10"].ToString().Trim(),DateTime.Now);
         cmd.ExecuteNonQuery();
         }
The second one is:
cmd.CommandText = string.Format(insertQuery, dr["col1"], dr["col2"], dr["col3"], dr["col4"], dr["col5"],dr["col6"];






Wednesday, November 30, 2011

Row edit,delete,update in grid view in asp.net using c#

Title: Edit,Delete,Update Data in Grid view in Asp.net using c#.net

Description:
As per previous articles we have seen how to export grid view data to excel in asp.net and how to bind data to drop down list in grid view.Now i would like to explain how to do edit,update in grid view using c#.Before going to start we have to set the grid view properties i:e(AutogenerateDeleteButton,AutogenerateEditButton,AutogenerateUpdateButton) to enable the auto generate Edit,Delete,Update buttons. The given example will show how to do the CRUD functionality on grid view data
Grid View properties:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True">
</asp:GridView>

Bind the data to grid view:
//page load event
if(page.isPostback==false)
{
dataset ds=null;
ds=(dataset)session["ds1"];
//session will contain dataset ds1 with data selected by user
if(ds!=null)
{
gvemp.datasource=ds.Tables["employee"];
gvemp.DataBind();
}
}      
Row Editing:
When user clicks on edit button post backtakes place,row editing event of grid view will be executed.This event will provide row index
protected void gremp_rowediting(object sender,EventArgs e)
{
dataset ds=(dstaset)session["ds1"];
gvemp.editindex=e.new editindex;
//e.newedit index:- will be provide index of row for which edit button is selected
gvemp.Datasource=Ds.Table["employee"];
gvemp.Databind();
}
Row Updating:
This will perform post back,row-updating event procedure of grid view will be executed
protected void gvemp-rowupdating(Object sender,EvenArgs e)
{
Textbox txt=(Textbox)gvemp.Rows[e.RowIndex].cells[3].controls[0];
//here i will update the third cell data in grid view
int avg=int.parse(txt.Text);
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex]["Average"]=avg;
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
//it will overwrite the session of Dataset
//Rearrange Gridview
gvemp.editIndex=-1;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}
Row Deleting:
This will perform post back,row-deleting event procedure of grid view will be executed
protected void gvemp-rowdeleting(Object sender,EvenArgs e)
{
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex].Delete();
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}

How to upload a file in asp.net using c#

Title:How to use upload control in asp.net

Description:
We can say "Sending file from client system to server system" as a definition .Mostly this control can be used as in  practical for uploading resume,image and attachment towards email.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>How to upload a file in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpLoad id="Fud" AlternateText="You cannot upload files" runat="server" />
<asp:Button id="btnupload" Text="Upload File" OnClick="btnupload_Click" runat="server" />
<asp:Label runat="server" Id="lblmessage" />
</form>
</body>
</html>

The properties and methods of File upload:

*has file--true-->File is upload
false-->File is not uploaded
*posted file--content type-->it returns file types
text/plain--->normal text file
text/xml---->XML file
application/msword-->doc file
save as(file path)--->it will save upload file in server system
Here i will shown to allow user to upload photos(image file type of gif) .For this i have taken file upload control and button server control in aspx page.


Code behind:

protected void btnupload_Click(object sender, EventArgs e)
{
Response.write(Fud.Hasfile);
Response.write(Fud.filename);
Response.write(Fud.posted file contenttype);
if(Fud.Hasfile)
{
if(Fud.Postedfile.ContentType=="image/gif")
{ 
Fud.postedfile.saveAs(server.mappath(".")+"\\"+Fud.filename);
lblmessage.text="upload successfully";
}
else
lblmessage.text="upload gif file";
}
else
lblmessagetext="file required";
}
}
Note:File upload control supports maximum of 4mb file size for uploading to server

Tuesday, November 29, 2011

Export data to excel in c#

Title:How to export grid view data to excel in asp.net using c#.net

Description:
Basically we can export the data to excel in two ways in asp.net with c#. One is using Download Format and Other one is using Microsoft.Office.Interop.Excel .In the Download format ,it  will render the grid view and export in XLST format.It is used when the data is export from grid view to excel.In Interop.Eexcel will create excel file dynamically and load the data into it.Exporting data to excel its pretty simple. Let's see how this can be done.For this i have taken data from database first then fill the existing data set.The following name space i have used for excel properties
Asp.Net Export to excel:
using Microsoft.Office.Interop.Excel;
Create Excel document:
Excel.Application App;
Excel.Workbook WorkBook;
Excel.Worksheet WorkSheet;
object misValue = System.Reflection.Missing.Value;
App = new Excel.Application();
WorkBook = App.Workbooks.Add(misValue);
WorkSheet = (Excel.Worksheet)WorkBook.Worksheets.get_Item(1);
Load the data into Excel file:
Here i will get the data into data set then it will load in to excel file using the following iteration.
for (int col = 0; col < dsreportdata.Tables[0].Columns.Count; col++)
{
for (int row = 0; row < dsreportdata.Tables[0].Rows.Count; row++)
{
WorkSheet.Cells[row + 12, col + 3] = dsreportdata.Tables[0].Rows[row].ItemArray[col].ToString();
}
}

Sunday, November 27, 2011

how to convert data types in csharp

The Microsoft .net providing a class "Converting" which can be used to convert from any data type into any other data type.Converting is a predefined class which is a part of FCL[Framework Class Library]converting class contains a collection of methods

convert.ToByte(value)
convert.ToChar(value)
convert.ToString(value)
convert.ToFloat(value)
convert.ToDouble(value)
Example on converting:
main()
{
for(i=65;i<=90;i++)
{
char c=convert.Tochar(i);
console.write(c);
}

Wednesday, November 23, 2011

An object reference is required for the non-static field, method, or property

Title: An object reference is required for the non-static field

Description:
Each console application has it's own static main method. If we want to call a non static method in a static method it is not possible straight away because the static methods can be called without instantiate and non-static methods should need object instantiated before it get called. So, For this reason we have to create an object of class in main method to call the non-static methods. Now I will show you a simple example to call the non static method in static method.

A small example:
//Program Class
class Program
{ 
public int add(int n1,int n2)
{
int result=n1+n2;
return result;
} 
}

//Main method
static void main()
{
Program p=new Program();
p.add(n1,n2);
//logic 
}

Bel