Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, August 30, 2012

Make a list box search


You need a listbox with items, a textbox and a button.


protected void Button1_Click(object sender, EventArgs e)
    {
        ListBoxPolicies.SelectedIndex = -1;

        for(int i=0; i< ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].ToString().Contains(TextBox1.Text))
            {
                ListBox1.SelectedIndex = i;
            }
        }
    }

Monday, November 7, 2011

Disable caching (Browser back button problem)


When the user hit the back button a locally cached copy of the previous page is retrieved without notifying the server. As a result the Info is out of sync.

Solution 1 --> Disable caching (do not work for all browsers)
Code to disable caching (to be executed everytime thepage is loaded)

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));   //--- (-1) means the page already expired
Response.Cache.SetNoStore();  //--tell the page not to cache the page
Response.AppendHeader("Pragma", "no-cache");  //---adds a header to the HTTP response object


Solution 2 --> Use timestamps or random numbers to track pages and detect when a page is current

Wednesday, August 24, 2011

Pad a string with zeros on the left/right in C# until completing n digits


Very simple way to pad with zeros until completing n digits
           
strMyString.PadLeft(n,'0');

Sample
string strMyString = "1234";
strMyString = strMyString.PadLeft(7,'0');


...will display "0001234"

Other notes: there is a .PadRight() function too.

Kill an Excel process in C#


foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
            {
                process.Kill();
                break;
            }
        }

Friday, August 19, 2011

Union of two dataTables and eliminate duplicates by using a customized IEqualityComparer


 public class StudentDataRowComparer : IEqualityComparer
    {

        #region IEqualityComparer Members

        public bool Equals(DataRow x, DataRow y)
        {
            return (x.Field("STUDENTID") == y.Field("STUDENTID"));
        }

        public int GetHashCode(DataRow obj)
        {
            return obj.ToString().GetHashCode();
        }

        #endregion
    }
 

How to call it
...
        //---Make an Union of both tables
        IEnumerable bothTables = dt1.AsEnumerable().Union(dt2.AsEnumerable());
                                DataTable dtUnion = bothTables.CopyToDataTable();

        //---Remove Duplicates
        var distinctStudents = dtUnion.AsEnumerable().Distinct( new StudentDataRowComparer());
                                DataTable dtFinal = distinctStudents.CopyToDataTable();

Tuesday, April 19, 2011

Sort a Listbox using IComparer in C#

What are we cooking today?
Sort a Listbox using IComparer in C# without loosing the value. 

RECIPE

The call
 SortList(MyListbox);

The Procedure

public void SortList(ListBox list)
{
        try
        {
            //---FROM LISTBOX TO LIST<>
            List ListItems = new List();
            foreach (ListItem lst in list.Items)
            {
                ListItems.Add(lst);
            }

            //---SORT LIST<>
            ListItemComparer listC = new ListItemComparer();
            ListItems.Sort(listC.Compare);

            //---CLEAR LISTBOX
            list.Items.Clear();

            //---ADD FROM ordered LIST<> to LISTBOX
            foreach (ListItem li in ListItems)
            {
                list.Items.Add(li);
            }
        }

        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
           
        }//--end catch
    }

The Icomparer: I am using this because a listitem has text and value, and we just want to order by the text, which could be a person's name or a product( the criteria could be also the value like price, personId, year...)


public class ListItemComparer : IComparer
{
    public int Compare(ListItem a, ListItem b)
    {
        int result = string.Compare(a.Text, b.Text);
        return result;
    }
}

Thursday, December 2, 2010

Clear all the TextBoxes in a form

What are we cooking today?
How to clear TextBoxes in a form that uses masterpages. (C#)


Recipe

This procedure clears all the textboxes in a form. Please note this works when using a masterpage:
  
    public void ClearTextboxesInForm(string strContentPlaceHolder)
    {
        foreach (Control control in Form.Controls) 
        {
            if (control.ID == strContentPlaceHolder) 
            {
                foreach (Control ctrl in control.Controls)
                {
                    if (ctrl is TextBox)  //---Find the textboxes 
                    {
                        ((TextBox)ctrl).Text = "";
                    }
                }
            }
        }
    }