Surendra Sharma

Surendra Sharma

Search This Blog

Tuesday, July 27, 2010

Add or Remove items from windows Combobox

public class ComboBoxItem

{

  
    private string display;

    private object data;

   
    public ComboBoxItem(string display, object data)


    {

      this.display = display;

      this.data = data;

    }

   
    public override string ToString()


    {

      return display;

    }


}





private
void Form1_Load(object sender, EventArgs e)

{

    comboBox1.Items.Add(new ComboBoxItem("a", 1));


    comboBox1.Items.Add(new ComboBoxItem("b", 2));

    comboBox1.Items.Add(new ComboBoxItem("c", 3));

    comboBox1.Items.Add(new ComboBoxItem("d", 4));

}

private void button1_Click(object sender, EventArgs e)


{

    comboBox1.Items.RemoveAt(2);

}

Exporting Grid view or data Grid to Excel ,Formatting cells with style sheet mso-number-format

When you export the gridview to Excel it looses it format. It means that maybe your gridview has string field which consisted of numbers say '002675'. But when you export the grid and see it in excel file you will find that the number changed to '2675'.

You can solve this issue using ‘mso-number-format’

e.Row.Cells[i].Attributes["style"] = "mso-number-format:\\#\\,\\#\\#0\\.00_\\)\\;\\[Black\\]\\\\(\\#\\,\\#\\#0\\.00\\\\)";
mso-number-format:"0" No Decimals
mso-number-format:"0\.00" 2 Decimals
mso-number-format:"mm\/dd\/yy" Date format
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM" D -T AMPM
mso-number-format:"Short Date" 05/06/-2008
mso-number-format:"Medium Date" 05-jan-2008
mso-number-format:"Short Time" 8:67
mso-number-format:"Medium Time" 8:67 am
mso-number-format:"Long Time" 8:67:25:00
mso-number-format:"Percent" Percent - two decimals
mso-number-format:"0\.E+00" Scientific Notation
mso-number-format:"\@" Text
mso-number-format:"\#\ ???\/???" Fractions - up to 3 digits (312/943)
mso-number-format:"\0022£\0022\#\,\#\#0\.00" £12.76
mso-number-format:"\#\,\#\#0\.00_ \;\[Red\]\-\#\,\#\#0\.00\ " 2 decimals, negative numbers in red and signed
(1.86 -1.66)
mso-number-format:”\\#\\,\\#\\#0\\.00_\\)\\;\\[Black\\]\\\\(\\#\\,\\#\\#0\\.00\\\\)” Accounting Format –5,(5)

Master Page Fix Height


<
form id="form2" runat="server">

<div>

<table border="0" width="100%">

<tr>

<td colspan="2" height="150" bgcolor="gray" valign="middle"  align="center">

HEADER

</td>

</tr>

<tr>

<td width="20%" bgcolor="silver">SIDEBAR</td>

<td width="80%" height="400" bgcolor="white">

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">

</asp:contentplaceholder>

</td>

</tr>

<tr>

<td colspan="2" align="center" height="20" bgcolor="gray">

FOOTER

</td>

</tr>

</table>

</div>

</form>

Friday, June 4, 2010

Regex for allowing only Alphabetics, numbers, apostrophe, spaces, dash for string having length 20

ValidationExpression="^[0-9a-zA-Z''\-'' '\s]{1,20}$"

To Display some ListItem in different colour in ListBox in ASP.NET

foreach (ListItem objTempItem in ListBox2.Items)

{

   //Code to change background colour of listitem

   //objTempItem.Attributes.Add("style", "background-color: RED");



  //Code to change text or foreground colour of listitem

  objTempItem.Attributes.Add("style","color:RED");

}

How to get Temporary Folder Path using .NET (C#)

How to get path of the current system's temporary folder using .NET (C#)
Temporary folders are useful to store simple logs during execution of the program. It is also used for storing the decompressed files before any operation. The folder location varies from OS to OS. The following C# snippet would help in retrieving the Temporary folder path

string sPath;

sPath =
Path.GetTempPath();

Console.WriteLine("Temporary Path := " + sPath );

Get filenames from all folders

Here is another way to get filenames from all folders, including subdirectories (notice the SearchOption.AllDirectories parametre):

// Process the list of files found in all directory.


string
[]
fileEntries = Directory.GetFiles(sourceDir,
"*", SearchOption.AllDirectories);


foreach

(string fileName in
fileEntries)


{

// do something with fileName


     
Console.WriteLine(fileName);


}


If you change the "*" to ex. "*.log" you will get all filenames that ends with ".log".

Show the Web site Icon in the Adress bar


<
head id="Head2"
runat="server">


   
<title>Untitled Page</title>


   
<link
href="t.png"
rel="shotcut icon"
/>

</head>

Create word document from Template & pass data from .NET


using

Microsoft.Office.Core;

using Word;




private

void ParseWord()


{


 


    Word.ApplicationClass
myWordApp = new Word.ApplicationClass();


    Word.Document myWordDoc
= new Word.Document();


 


   
object missing = System.Reflection.Missing.Value; // our
'void' value


   
object filename =
@"E:\My Files\WordTest\Master5.dot"
; // our
word template


   
object destination =
@"E:\My Files\WordTest\ABC4.doc"
; 
// our target filename


   
object notTrue = false;  // our
boolean false

 

 


   
string myText =
"Hello World!!"
;


   
// the sample text we want as replacement

 


    myWordApp.Visible =
false;  //
tell word not to show itself

 


    myWordDoc =
myWordApp.Documents.Add( // load the template into a
document workspace


                         
ref filename,  // and
reference it through our myWordDoc


                         
ref missing,


                         
ref missing,


                         
ref missing);


 


   
// count how many fields we have to update


   
foreach (Field myField
in
myWordDoc.Fields)


    {


       
myField.Select();


       
string str = myField.Code.Text;


       
myWordApp.Selection.TypeText(DateTime.Now.ToString());


    }


 


   
//


   
// now the last touch.. save and close


   
//


    myWordDoc.SaveAs(


            
ref destination,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


             ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing,


            
ref missing);


 


   
// quit word


   
myWordApp.Application.Quit(


            
ref notTrue,


            
ref missing,


            
ref missing);

}

Set Server Side Label Control Text from Javascript

document.getElementById('<%=lblDateSelect.ClientID%>').innerText = 'Please select From Date' ;

Thursday, May 13, 2010

How to set text to a Password TextBox in ASP.NET

txtPassword.Attributes["value"] = "Password123";

Get the difference of month between two dates


private
static int monthDifference(DateTime startDate, DateTime endDate)

{       int monthsApart =
12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
      return Math.Abs(monthsApart);



}

To solve apostrophe problem in where condition of SQL Statement


If ur query contain single apostrophe like this

SELECT * FROM Products WHERE ProductName = 'King's Jalepenos'

Then replace ur single apostrophe with two apostrophe like

SELECT * FROM Products WHERE ProductName ='King''s Jalepenos'



Better do it in C# coding as follows


string

str = "King''s Jalepenos";

str= str.Replace("'","''");

WinCV.exe - viewing the contents of any DOT NET namespace

WinCV.exe is a tool for viewing the contents of any DOT NET namespace. It is resides in C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin

Memory Management for ASP.NET & making space for C: drive

By Default ASP.Net store all the page requested at C:\Documents and Settings\SURENDRAS\ASPNET\Local Settings\Temp. So delete all the files within this folder for improving performance & for making space in C drive.

Create HTML Table in ASP.NET


Table one Table & say Run as a server control. Its Id is 
tblIntangiblesInner





public

void FillIntangibleTable()


            {


                 ArrayList arrList = null;


                 arrList = (ArrayList)LoadAllIntangibles();


                 foreach (object
item in arrList)


                 {


                       HtmlTableRow theRow = new HtmlTableRow();


                       HtmlTableCell []theCell = new
HtmlTableCell[2];


                       theCell[0] = new HtmlTableCell();


                       theCell[1] = new HtmlTableCell();


                       theCell[0].Width = "5%";


                       theCell[1].Width = "95%";


                       theCell[0].InnerHtml = "&nbsp;";


                       theCell[1].InnerHtml = "<a
href=default.aspx?GSIN="
+item.ToString()+">"
+ item.ToString() + "</a>";


                       theRow.Cells.Add(theCell[0]);


                       theRow.Cells.Add(theCell[1]);


                       tblIntangiblesInner.Rows.Add(theRow);


                 }



           }






public

ArrayList LoadAllIntangibles()


            {


                 System.Collections.ArrayList obj = new
System.Collections.ArrayList();


                 obj.Add("2");


                 obj.Add("3");


                 obj.Add("4");


                 obj.Add("5");


                 obj.Add("6");


                 obj.Add("7");


                 return obj;



           }




Printting a file in .NET

Dim psiPrint As New System.Diagnostics.ProcessStartInfo()
psiPrint.Verb = "print"
psiPrint.WindowStyle = ProcessWindowStyle.Hidden
psiPrint.FileName = "C:\MyFile.pdf"
psiPrint.UseShellExecute = True
System.Diagnostics.Process.Start(psiPrint)

Select CASE Statement in SQL


SELECT (CASE chrSexo WHEN 'M' THEN 'Masculino'
         WHEN 'F' THEN 'Femenino'
         END
) AS Sexo
FROM tblDatos


Redirecting User to Login Page After Session Timeouts


Refreshing any page after certain interval

     For
refreshing any page after certain interval, you need to use client side script
only. You cant do this in server side, The reason being that the page has been
served to the client, end of request.  The web is stateless; until the user
comes back and initiates another request the server can't do anything. So we
need to do this refreshing activity from client side only. There are two ways to
achieve this,

                   
1. Using Window.setTimeout method

                   
2. Using Meta Tag - Refresh. 

Using
Window.setTimeout method:

              DHTML Window object has a
method called "setTimeout" which  evaluates an expression after a specified
number of milliseconds has elapsed. With the help of this method, you can run
the client side script window.location.href="somepage" to redirect page in the
current window. SetTimeout accepts three parameters.


vCode


Required. Variant that
specifies the function pointer or string that indicates the code to be executed
when the specified interval has elapsed.


iMilliSeconds


Required. Integer that
specifies the number of milliseconds.


sLanguage


Optional. String that
specifies one of the following values:




JScript


Language is JScript.



VBScript


Language is VBScript.



JavaScript


Language is JavaScript.


             You need to call
this method in body load and start the timer( by calling setTimeout method).
This timer will elapse depending upon the second parameter for this method. When
it is elapsed, it will fire the script which is given as first parameter. So you
need to add this to the body element onload method. For adding client side event
to body tag in asp.net you need to follow this methos.

1. Declare the body tag in
html window as server control by specifing runat attribute and give an id to
that tag.

                               
<body runat="server" id= "body">< /P>< /FONT>

2. In the code behind,
declare this element as htmlgenericcontrol like this.            

  Protected WithEvents body As
System.Web.UI.HtmlControls.HtmlGenericControl
    

3. Finally add
the following code in your page_load event handler, this will add the client
side handler for body tag.

 body.Attributes.Add("onLoad",
"window.setTimeout(""window.location.href='<somepage>.aspx'"",5000);")
     

This method will
refresh the page to the specified location after 5 secs. The disadvantage of
this method is, this might not work in some lower end browsers. So you need to
go for other method i.e. by using Meta Tags.

Using
Meta Tag - Refresh

   

Another way for refreshing the page after certain interval is by using meta tag
- Refresh. This tag specifies a delay in seconds before the browser
automatically reloads the document. Optionally, specifies an alternative URL to
load. Example

              
<META HTTP-EQUIV="Refresh"
CONTENT="3;URL=http://www.some.org/some.html">

In ASP.NET, you
can add headers in code behind using this method.

            
Response.AppendHeader("Refresh", "10;
URL=.aspx")

This method will
reload the current window after interval mentioned in the second parameter to
the page which is mentioned as URL to refresh. In this case page will be
refreshed after 10 seconds.

Redirecting User To Login Page after Session Timeouts.

Redirecting user
to login page after session timeout is similar to refreshing the page after
certain intervals method. Only thing which will differ is that calculating time
after which the page has to be redirected. Hence time can be calculated using
Session.timeout property which will give us session timeout value for that
session. Add some grace timings to that value and redirect the user to the login
page automatically.

Using
Window.setTimeout method


body.Attributes.Add("onLoad",
"window.setTimeout(""window.location.href='login.aspx'""," & (Session.Timeout *
60 * 1000) + 10000 & ");")

Using
Meta Tag - Refresh


Response.AppendHeader("Refresh", Convert.ToString((Session.Timeout * 60) + 10) &
"; URL=Login.aspx")

Both these methods will redirect the
user to login page  after session timeout + 10 seconds. This is how you can
redirect the user to login page after session timeout without user interaction.

Wednesday, May 5, 2010

Accessing Web site in IIS

Hi you won't be able to access your machine by using localhost. Localhost points to your local machines standard ip address of 127.0.0.1. To access the webserver on your vista machine you will need to browse to the ip address or machine name of your vista machine. i.e. http://192.168.0.1/ or http://vistamachinename/

Cannot publish the web site using Visual Studio (publish failed)

Display the output window. VS 2008 - View -> Output.

When you publish it will give you all the errors.

Songs for programming concepts

Local variable
Jeena Yahan Marna Yahan,
Iske siva Jana kaahan.

Global variable
Musafir hoon yaaron,
na ghar hai na thikana

The debugger
Jab koi baat bigad jaye
Jab koi mushkil pad jaye
Tum dena saath mera hamnawaz

Grid with line numbers

<columns>


       
<asp:templatecolumn
ID="templatecolumn1"
runat="server"
headertext="Row Number">

<itemtemplate>

<span><%# Container.ItemIndex+1 %></span>

</itemtemplate>

</asp:templatecolumn>

</columns>

Datagrid Sort Example


void
MyDataGrid_Sort(Object sender, DataGridSortCommandEventArgs e) {


    SortField = (string)e.SortExpression;

    BindGrid();

}




DataView dv = new DataView(dt);

dv.Sort = SortField;

return dv;


Tuesday, May 4, 2010

To get month name from datetime picker in VB.NET

dim str as string=MonthName(dtpAttendance_Date.Value.Month)

To get month name from datefield of a Table in SQL

SELECT DATENAME(month, getdate()) AS 'Month Name'

Command for Redirecting all the file of a folder in a reverse order of Datewise.

D:\> dir *.cs /B /O-D>C:\abc.txt

To Convert variable of one datatype to other in SQL.


DECLARE
@mybin1 binary(5), @mybin2 binary(5)
SET @mybin1 = 0xFF
SET @mybin2 = 0xA5
-- No CONVERT or CAST function is necessary because this example concatenates two binary strings.
SELECT @mybin1 + @mybin2
-- A CONVERT or CAST function is necessary because this example concatenates two binary strings plus a space.
SELECT CONVERT(varchar(5), @mybin1) + ' ' + CONVERT(varchar(5), @mybin2)
-- Here is the same conversion using CAST
SELECT CAST(@mybin1 AS varchar(5)) + ' ' + CAST(@mybin2 AS varchar(5))

New Line in Multiline TextBox in C#

TextBox1.Text ="RAM" + System.Environment.NewLine;

TextBox1.Text +="RAM" + System.Environment.NewLine;

OR

TextBox1.Text ="RAM" + "\r\n";

TextBox1.Text +="RAM" + "\r\n";


 

Microsoft Agent in C#





AgentObjects.IAgentCtlCharacter Character;


string

sChar = @"C:\WINNT\msagent\chars\merlin.acs";


agtAgent.Characters.Load("merlin", sChar);


Character = agtAgent.Characters["merlin"];


Character.Show(null);


Character.Play("sad");

Character.Speak("Task
which are yet to completed are "
, null);









Check selected value in CheckListBox in ASP.NET


for
(int counter = 0; counter < ChecklistBox1.Items.Count; Counter++)

{

    if (ChecklistBox1.Items[counter].Selected == true)

    {

       //True part

    }

    else

    {

       //false Part

    }

}


To get exact no. of days in particular month of a year.

dim Noofday as integar=
dtpSalarySlip.Value.DaysInMonth(dtpSalarySlip.Value.Year,
dtpSalarySlip.Value.Month)

To extract only time from the datetime field

SELECT Convert(VARCHAR(10),Getdate(), 108)

To get only date part from datetime field in sql stmt.

CAST(CONVERT(varchar(100), dbo.Attendance_Detail.Attendance_Date, 101) AS datetime) AS Attendance_Date

Enter data in subitem of particular item(i.e. rows) in Listview

Solution :->
listview1.Items[iRow-1].SubItems[2].Text =sCallDuration;
listview1.Items[iRow-1].SubItems[3].Text= sStatus;