Tag: csharp

  • Convert from Double to DateTime

    In Delphi we can cast the double value as datetime:

    var
      dbl: Double;
      dt: TDateTime;
    begin
      dbl := 65985.3333;
      dt := dbl;
    end;

    But in .NET we need call the  FromOADate method for DateTime class:

      Double dbl = 65985.3333;
      DateTime dt = DateTime.FromOADate(dbl)
  • How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control

    http://msdn.microsoft.com/ru-ru/library/ms171619(en-us,VS.80).aspx

     using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Windows.Forms.VisualStyles;

    class Form1 : Form
    {
        private DataGridView dataGridView1 = new DataGridView();

        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.AutoSize = true;
            this.Load += new EventHandler(Form1_Load);
        }

        public void Form1_Load(object sender, EventArgs e)
        {
            DataGridViewCheckBoxColumn column0 =
                new DataGridViewCheckBoxColumn();
            DataGridViewDisableButtonColumn column1 =
                new DataGridViewDisableButtonColumn();
            column0.Name = “CheckBoxes”;
            column1.Name = “Buttons”;
            dataGridView1.Columns.Add(column0);
            dataGridView1.Columns.Add(column1);
            dataGridView1.RowCount = 8;
            dataGridView1.AutoSize = true;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment =
                DataGridViewContentAlignment.MiddleCenter;

            // Set the text for each button.
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Cells[“Buttons”].Value =
                    “Button ” + i.ToString();
            }

            dataGridView1.CellValueChanged +=
                new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
            dataGridView1.CurrentCellDirtyStateChanged +=
                new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
            dataGridView1.CellClick +=
                new DataGridViewCellEventHandler(dataGridView1_CellClick);

            this.Controls.Add(dataGridView1);
        }

        // This event handler manually raises the CellValueChanged event
        // by calling the CommitEdit method.
        void dataGridView1_CurrentCellDirtyStateChanged(object sender,
            EventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
            {
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        // If a check box cell is clicked, this event handler disables 
        // or enables the button in the same row as the clicked cell.
        public void dataGridView1_CellValueChanged(object sender,
            DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == “CheckBoxes”)
            {
                DataGridViewDisableButtonCell buttonCell =
                    (DataGridViewDisableButtonCell)dataGridView1.
                    Rows[e.RowIndex].Cells[“Buttons”];

                DataGridViewCheckBoxCell checkCell =
                    (DataGridViewCheckBoxCell)dataGridView1.
                    Rows[e.RowIndex].Cells[“CheckBoxes”];
                buttonCell.Enabled = !(Boolean)checkCell.Value;

                dataGridView1.Invalidate();
            }
        }

        // If the user clicks on an enabled button cell, this event handler 
        // reports that the button is enabled.
        void dataGridView1_CellClick(object sender,
            DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == “Buttons”)
            {
                DataGridViewDisableButtonCell buttonCell =
                    (DataGridViewDisableButtonCell)dataGridView1.
                    Rows[e.RowIndex].Cells[“Buttons”];

                if (buttonCell.Enabled)
                {
                    MessageBox.Show(dataGridView1.Rows[e.RowIndex].
                        Cells[e.ColumnIndex].Value.ToString() +
                        ” is enabled”);
                }
            }
        }
    }

    public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn
    {
        public DataGridViewDisableButtonColumn()
        {
            this.CellTemplate = new DataGridViewDisableButtonCell();
        }
    }

    public class DataGridViewDisableButtonCell : DataGridViewButtonCell
    {
        private bool enabledValue;
        public bool Enabled
        {
            get
            {
                return enabledValue;
            }
            set
            {
                enabledValue = value;
            }
        }

        // Override the Clone method so that the Enabled property is copied.
        public override object Clone()
        {
            DataGridViewDisableButtonCell cell =
                (DataGridViewDisableButtonCell)base.Clone();
            cell.Enabled = this.Enabled;
            return cell;
        }

        // By default, enable the button cell.
        public DataGridViewDisableButtonCell()
        {
            this.enabledValue = true;
        }

        protected override void Paint(Graphics graphics,
            Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
            DataGridViewElementStates elementState, object value,
            object formattedValue, string errorText,
            DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {
            // The button cell is disabled, so paint the border, 
            // background, and disabled button for the cell.
            if (!this.enabledValue)
            {
                // Draw the cell background, if specified.
                if ((paintParts & DataGridViewPaintParts.Background) ==
                    DataGridViewPaintParts.Background)
                {
                    SolidBrush cellBackground =
                        new SolidBrush(cellStyle.BackColor);
                    graphics.FillRectangle(cellBackground, cellBounds);
                    cellBackground.Dispose();
                }

                // Draw the cell borders, if specified.
                if ((paintParts & DataGridViewPaintParts.Border) ==
                    DataGridViewPaintParts.Border)
                {
                    PaintBorder(graphics, clipBounds, cellBounds, cellStyle,
                        advancedBorderStyle);
                }

                // Calculate the area in which to draw the button.
                Rectangle buttonArea = cellBounds;
                Rectangle buttonAdjustment =
                    this.BorderWidths(advancedBorderStyle);
                buttonArea.X += buttonAdjustment.X;
                buttonArea.Y += buttonAdjustment.Y;
                buttonArea.Height -= buttonAdjustment.Height;
                buttonArea.Width -= buttonAdjustment.Width;

                // Draw the disabled button.               
                ButtonRenderer.DrawButton(graphics, buttonArea,
                    PushButtonState.Disabled);

                // Draw the disabled button text.
                if (this.FormattedValue is String)
                {
                    TextRenderer.DrawText(graphics,
                        (string)this.FormattedValue,
                        this.DataGridView.Font,
                        buttonArea, SystemColors.GrayText);
                }
            }
            else
            {
                // The button cell is enabled, so let the base class
                // handle the painting.
                base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                    elementState, value, formattedValue, errorText,
                    cellStyle, advancedBorderStyle, paintParts);
            }
        }
    }

  • How to: Host Controls in Windows Forms DataGridView Cells

    http://msdn.microsoft.com/ru-ru/library/7tas5c80(en-us,VS.80).aspx

    using System; 
    using System.Windows.Forms; 
    
    public class CalendarColumn : DataGridViewColumn 
    { 
        public CalendarColumn() : base(new CalendarCell()) 
        { 
        } 
        public override DataGridViewCell CellTemplate 
        { 
            get 
            { 
                return base.CellTemplate; 
            } 
            set 
            { 
                // Ensure that the cell used for the template is a CalendarCell. 
                if (value != null && 
                    !value.GetType().IsAssignableFrom(typeof(CalendarCell))) 
                { 
                    throw new InvalidCastException("Must be a CalendarCell"); 
                } 
                base.CellTemplate = value; 
            } 
        } 
    } 
    public class CalendarCell : DataGridViewTextBoxCell 
    { 
        public CalendarCell() 
            : base() 
        { 
            // Use the short date format. 
            this.Style.Format = "d"; 
        } 
        public override void InitializeEditingControl(int rowIndex, object 
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) 
        { 
            // Set the value of the editing control to the current cell value. 
            base.InitializeEditingControl(rowIndex, initialFormattedValue, 
                dataGridViewCellStyle); 
            CalendarEditingControl ctl = 
                DataGridView.EditingControl as CalendarEditingControl; 
            ctl.Value = (DateTime)this.Value; 
        } 
        public override Type EditType 
        { 
            get 
            { 
                // Return the type of the editing contol that CalendarCell uses. 
                return typeof(CalendarEditingControl); 
            } 
        } 
        public override Type ValueType 
        { 
            get 
            { 
                // Return the type of the value that CalendarCell contains. 
                return typeof(DateTime); 
            } 
        } 
        public override object DefaultNewRowValue 
        { 
            get 
            { 
                // Use the current date and time as the default value. 
                return DateTime.Now; 
            } 
        } 
    } 
    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl 
    { 
        DataGridView dataGridView; 
        private bool valueChanged = false; 
        int rowIndex; 
        public CalendarEditingControl() 
        { 
            this.Format = DateTimePickerFormat.Short; 
        } 
        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property. 
        public object EditingControlFormattedValue 
        { 
            get 
            { 
                return this.Value.ToShortDateString(); 
            } 
            set 
            { 
                if (value is String) 
                { 
                    this.Value = DateTime.Parse((String)value); 
                } 
            } 
        } 
        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method. 
        public object GetEditingControlFormattedValue( 
            DataGridViewDataErrorContexts context) 
        { 
            return EditingControlFormattedValue; 
        } 
        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. 
        public void ApplyCellStyleToEditingControl( 
            DataGridViewCellStyle dataGridViewCellStyle) 
        { 
            this.Font = dataGridViewCellStyle.Font; 
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor; 
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor; 
        } 
        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property. 
        public int EditingControlRowIndex 
        { 
            get 
            { 
                return rowIndex; 
            } 
            set 
            { 
                rowIndex = value; 
            } 
        } 
        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method. 
        public bool EditingControlWantsInputKey( 
            Keys key, bool dataGridViewWantsInputKey) 
        { 
            // Let the DateTimePicker handle the keys listed. 
            switch (key & Keys.KeyCode) 
            { 
                case Keys.Left: 
                case Keys.Up: 
                case Keys.Down: 
                case Keys.Right: 
                case Keys.Home: 
                case Keys.End: 
                case Keys.PageDown: 
                case Keys.PageUp: 
                    return true; 
                default: 
                    return false; 
            } 
        } 
        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method. 
        public void PrepareEditingControlForEdit(bool selectAll) 
        { 
            // No preparation needs to be done. 
        } 
        // Implements the IDataGridViewEditingControl 
        // .RepositionEditingControlOnValueChange property. 
        public bool RepositionEditingControlOnValueChange 
        { 
            get 
            { 
                return false; 
            } 
        } 
        // Implements the IDataGridViewEditingControl 
        // .EditingControlDataGridView property. 
        public DataGridView EditingControlDataGridView 
        { 
            get 
            { 
                return dataGridView; 
            } 
            set 
            { 
                dataGridView = value; 
            } 
        } 
        // Implements the IDataGridViewEditingControl 
        // .EditingControlValueChanged property. 
        public bool EditingControlValueChanged 
        { 
            get 
            { 
                return valueChanged; 
            } 
            set 
            { 
                valueChanged = value; 
            } 
        } 
        // Implements the IDataGridViewEditingControl 
        // .EditingPanelCursor property. 
        public Cursor EditingPanelCursor 
        { 
            get 
            { 
                return base.Cursor; 
            } 
        } 
        protected override void OnValueChanged(EventArgs eventargs) 
        { 
            // Notify the DataGridView that the contents of the cell 
            // have changed. 
            valueChanged = true; 
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true); 
            base.OnValueChanged(eventargs); 
        } 
    } 
    public class Form1 : Form 
    { 
        private DataGridView dataGridView1 = new DataGridView();
        [STAThreadAttribute()] 
        public static void Main() 
        { 
            Application.Run(new Form1()); 
        } 
        public Form1() 
        { 
            this.dataGridView1.Dock = DockStyle.Fill; 
            this.Controls.Add(this.dataGridView1); 
            this.Load += new EventHandler(Form1_Load); 
            this.Text = "DataGridView calendar column demo"; 
        } 
        private void Form1_Load(object sender, EventArgs e) 
        { 
            CalendarColumn col = new CalendarColumn(); 
            this.dataGridView1.Columns.Add(col); 
            this.dataGridView1.RowCount = 5; 
            foreach (DataGridViewRow row in this.dataGridView1.Rows) 
            { 
                row.Cells[0].Value = DateTime.Now; 
            } 
        } 
    }
  • DreamSpark нахаляву

    Microsoft раздает нахаляву всем студентам-аспирантам свои девелоперские тулзы:

    http://blogs.gotdotnet.ru/personal/kichik/PermaLink.aspx?guid=18aa5b84-09c2-48e8-aec7-8ea75f72148f
    http://dreamspark.ru

    В настоящее время по программе DreamSpark доступны следующие инструменты:

    • Visual Studio 2008 Professional Edition
    • Visual Studio 2005 Professional Ediation
    • SQL Server 2008 Developer
    • Windows Server 2008 Standard
    • Windows Server 2003
    • Expression Studio 2
    • XNA Game Studio 2.0
  • to get the current directory

    String s = Directory.GetCurrentDirectory()

    For Compact .NET:
    String s = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

  • to read the IMEI in Compact .NET

    //Import cellcore.dll
    
    [DllImport("cellcore.dll")]
     internal static extern int lineGetGeneralInfo(IntPtr hLine, byte[] bCache);
    
    // code to get IMEI
    private void getIMEIInfo()
    {
    string IMEI;
    Tapi t = new Tapi();
    t.Initialize();
    Line _line = t.CreateLine(0, LINEMEDIAMODE.INTERACTIVEVOICE, LINECALLPRIVILEGE.MONITOR);
    
    byte[] buffer = new byte[512];
    //write size
    BitConverter.GetBytes(512).CopyTo(buffer, 0);
    
    if (lineGetGeneralInfo(_line.hLine, buffer) != 0)
    {
    throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error(), "TAPI Error: " + System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString("X"));
    }
    
    int serialsize = BitConverter.ToInt32(buffer, 36);
    int serialoffset = BitConverter.ToInt32(buffer, 40);
    IMEI = System.Text.Encoding.Unicode.GetString(buffer, serialoffset, serialsize);
    IMEI = IMEI.Substring(0, IMEI.IndexOf(Convert.ToChar(0)));
    
    AppSettings.SetIMEI(IMEI);
    _line.Dispose();
    t.Shutdown();
    }
    

    To get the TAPILib: http://www.alexfeinman.com/download.asp?doc=tapi1.1.zip