DG CurrentCell.ColumnNumber - HELP!!

I have a windows (specifically mobile) datagrid - I am trying to force/set the CurrentCell.ColumnNumber to 0 but when I do, I get the following: "NullReferenceException Was Handled"

This is the code that works but not what I need:
grid[currentCell.RowNumber, currentCell.ColumnNumber] = txtEdit.Text;

This is really what I want but throws the error:
grid[currentCell.RowNumber, 0] = txtEdit.Text;


Answer this question

DG CurrentCell.ColumnNumber - HELP!!

  • Oktavia

    Did you try running the application under the debugger to see where the source of the NullReferenceException was

    How about a Stack trace

    Can you post the full code so we can give you some more pointers


  • Wasting Body

    I did not run your code, but I can tell you right away you have at least one issue:

    DataRow dr = ds.Tables[0].Rows[grid.CurrentRowIndex];

    You're using row index in the grid to access rows in the table and they are not the same. Your code might work once or twice, but will blow up eventually. Please see this for details:



  • Thomas Mikolajczyk

    Iyla - thanks, I will give that a try - also, I think that I fugured my original post out - I was trying to set the currentcell.column to 0 when I really needed to set it to 1- I thought that cells/columns started with zero as well
  • chr1zis

    For what it is worth - here is the mess that is my source code - again, the error is blowing up at the line above (previous post):

    //////////////////////////////////////////////////////////////////////////////

    using System;

    using System.Data.SqlServerCe;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    using System.IO;

    using RIO.Data;

    using RIO.GUI;

    using System.Reflection;

    namespace RIO

    {

    /// <summary>

    /// This is the main RIO (startup) form.

    /// </summary>

    public class frmMainq : System.Windows.Forms.Form

    {

    #region Declarations

    private System.Windows.Forms.TextBox txtEdit;

    private System.Windows.Forms.DataGrid grid;

    private Microsoft.WindowsCE.Forms.InputPanel sip;

    private string strAccountName = string.Empty;

    protected DialogResult dlgRes;

    private Panel pnlHeader;

    private Label lblAccountName;

    private MainMenu mainMenu1;

    private MenuItem miRIO;

    private MenuItem miExitRIO;

    private MenuItem miAccount;

    private MenuItem miAccountName;

    private MenuItem miMode;

    private MenuItem miAllItems;

    private MenuItem miItemsWithPars;

    private MenuItem miUnInvItems;

    private MenuItem miModeSep1;

    private MenuItem miInventory;

    private MenuItem miOrder;

    private MenuItem miBoth;

    private MenuItem miReceive;

    private MenuItem menuItem2;

    private Label lblInventoryValue2;

    private Label lblOrderValue2;

    private Label lblPrice2;

    private Label lblItemHeader;

    private Label lblOrderValue;

    private Label lblInventoryValue;

    private Label lblPrice;

    private System.ComponentModel.IContainer components = null;

    private MenuItem miXML;

    private MenuItem menuItem3;

    private bool bEditing;

    private bool vsbEnabled, hsbEnabled;

    private VScrollBar vsb;

    private HScrollBar hsb;

    private int editColumn = -1;

    RIO.Data.clsData data = new clsData();

    DataSet ds = new DataSet();

    private string appPath

    {

    get { return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); }

    }

    #endregion

    #region Constructor

    public frmMainq()

    {

    InitializeComponent();

    this.components = new System.ComponentModel.Container();

    }

    #endregion

    #region Dispose

    /// <summary>

    /// Clean up any resources being used.

    /// </summary>

    protected override void Dispose(bool disposing)

    {

    if (disposing && (components != null))

    {

    components.Dispose();

    }

    base.Dispose(disposing);

    }

    #endregion

    #region Windows Form Designer generated code

    /// <summary>

    /// Required method for Designer support - do not modify

    /// the contents of this method with the code editor.

    /// </summary>

    private void InitializeComponent()

    {

    this.grid = new System.Windows.Forms.DataGrid();

    this.txtEdit = new System.Windows.Forms.TextBox();

    this.sip = new Microsoft.WindowsCE.Forms.InputPanel();

    this.pnlHeader = new System.Windows.Forms.Panel();

    this.lblAccountName = new System.Windows.Forms.Label();

    this.mainMenu1 = new System.Windows.Forms.MainMenu();

    this.miRIO = new System.Windows.Forms.MenuItem();

    this.miExitRIO = new System.Windows.Forms.MenuItem();

    this.miAccount = new System.Windows.Forms.MenuItem();

    this.miAccountName = new System.Windows.Forms.MenuItem();

    this.miMode = new System.Windows.Forms.MenuItem();

    this.miAllItems = new System.Windows.Forms.MenuItem();

    this.miItemsWithPars = new System.Windows.Forms.MenuItem();

    this.miUnInvItems = new System.Windows.Forms.MenuItem();

    this.miModeSep1 = new System.Windows.Forms.MenuItem();

    this.miInventory = new System.Windows.Forms.MenuItem();

    this.miOrder = new System.Windows.Forms.MenuItem();

    this.miBoth = new System.Windows.Forms.MenuItem();

    this.miReceive = new System.Windows.Forms.MenuItem();

    this.menuItem2 = new System.Windows.Forms.MenuItem();

    this.menuItem3 = new System.Windows.Forms.MenuItem();

    this.miXML = new System.Windows.Forms.MenuItem();

    this.lblInventoryValue2 = new System.Windows.Forms.Label();

    this.lblOrderValue2 = new System.Windows.Forms.Label();

    this.lblPrice2 = new System.Windows.Forms.Label();

    this.lblItemHeader = new System.Windows.Forms.Label();

    this.lblOrderValue = new System.Windows.Forms.Label();

    this.lblInventoryValue = new System.Windows.Forms.Label();

    this.lblPrice = new System.Windows.Forms.Label();

    this.lblUnits = new System.Windows.Forms.Label();

    this.lblPackSize = new System.Windows.Forms.Label();

    this.pnlHeader.SuspendLayout();

    this.SuspendLayout();

    //

    // grid

    //

    this.grid.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));

    this.grid.Location = new System.Drawing.Point(-1, 99);

    this.grid.Name = "grid";

    this.grid.RowHeadersVisible = false;

    this.grid.Size = new System.Drawing.Size(242, 170);

    this.grid.TabIndex = 2;

    this.grid.Click += new System.EventHandler(this.grid_Click);

    this.grid.CurrentCellChanged += new System.EventHandler(this.txtEdit_TextChanged);

    //

    // txtEdit

    //

    this.txtEdit.BorderStyle = System.Windows.Forms.BorderStyle.None;

    this.txtEdit.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.txtEdit.Location = new System.Drawing.Point(192, 0);

    this.txtEdit.Name = "txtEdit";

    this.txtEdit.Size = new System.Drawing.Size(40, 20);

    this.txtEdit.TabIndex = 0;

    this.txtEdit.Visible = false;

    this.txtEdit.TextChanged += new System.EventHandler(this.txtEdit_TextChanged);

    //

    // sip

    //

    this.sip.EnabledChanged += new System.EventHandler(this.sip_EnabledChanged);

    //

    // pnlHeader

    //

    this.pnlHeader.BackColor = System.Drawing.SystemColors.MenuText;

    this.pnlHeader.Controls.Add(this.lblAccountName);

    this.pnlHeader.Location = new System.Drawing.Point(0, 0);

    this.pnlHeader.Name = "pnlHeader";

    this.pnlHeader.Size = new System.Drawing.Size(240, 28);

    //

    // lblAccountName

    //

    this.lblAccountName.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);

    this.lblAccountName.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;

    this.lblAccountName.Location = new System.Drawing.Point(3, 7);

    this.lblAccountName.Name = "lblAccountName";

    this.lblAccountName.Size = new System.Drawing.Size(234, 20);

    //

    // mainMenu1

    //

    this.mainMenu1.MenuItems.Add(this.miRIO);

    this.mainMenu1.MenuItems.Add(this.miAccount);

    this.mainMenu1.MenuItems.Add(this.miMode);

    this.mainMenu1.MenuItems.Add(this.miReceive);

    this.mainMenu1.MenuItems.Add(this.menuItem2);

    //

    // miRIO

    //

    this.miRIO.MenuItems.Add(this.miExitRIO);

    this.miRIO.Text = "RIO";

    //

    // miExitRIO

    //

    this.miExitRIO.Text = "Exit RIO";

    this.miExitRIO.Click += new System.EventHandler(this.miExitRIO_Click_1);

    //

    // miAccount

    //

    this.miAccount.MenuItems.Add(this.miAccountName);

    this.miAccount.Text = "Account";

    //

    // miAccountName

    //

    this.miAccountName.Text = "";

    //

    // miMode

    //

    this.miMode.MenuItems.Add(this.miAllItems);

    this.miMode.MenuItems.Add(this.miItemsWithPars);

    this.miMode.MenuItems.Add(this.miUnInvItems);

    this.miMode.MenuItems.Add(this.miModeSep1);

    this.miMode.MenuItems.Add(this.miInventory);

    this.miMode.MenuItems.Add(this.miOrder);

    this.miMode.MenuItems.Add(this.miBoth);

    this.miMode.Text = "Mode";

    //

    // miAllItems

    //

    this.miAllItems.Text = "All Items";

    //

    // miItemsWithPars

    //

    this.miItemsWithPars.Text = "Only Items with Pars";

    this.miItemsWithPars.Click += new System.EventHandler(this.miItemsWithPars_Click);

    //

    // miUnInvItems

    //

    this.miUnInvItems.Text = "Only Uninventoried Items";

    this.miUnInvItems.Click += new System.EventHandler(this.miUnInvItems_Click);

    //

    // miModeSep1

    //

    this.miModeSep1.Text = "-";

    //

    // miInventory

    //

    this.miInventory.Text = "Inventory";

    this.miInventory.Click += new System.EventHandler(this.Mode_Change);

    //

    // miOrder

    //

    this.miOrder.Text = "Order";

    this.miOrder.Click += new System.EventHandler(this.Mode_Change);

    //

    // miBoth

    //

    this.miBoth.Text = "Both";

    this.miBoth.Click += new System.EventHandler(this.Mode_Change);

    //

    // miReceive

    //

    this.miReceive.Text = "Receive";

    //

    // menuItem2

    //

    this.menuItem2.MenuItems.Add(this.menuItem3);

    this.menuItem2.MenuItems.Add(this.miXML);

    this.menuItem2.Text = "Help";

    //

    // menuItem3

    //

    this.menuItem3.Text = "Reset Data from Desktop";

    this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);

    //

    // miXML

    //

    this.miXML.Text = "Generate Data for Desktop";

    this.miXML.Click += new System.EventHandler(this.miXML_Click);

    //

    // lblInventoryValue2

    //

    this.lblInventoryValue2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblInventoryValue2.Location = new System.Drawing.Point(89, 80);

    this.lblInventoryValue2.Name = "lblInventoryValue2";

    this.lblInventoryValue2.Size = new System.Drawing.Size(53, 14);

    //

    // lblOrderValue2

    //

    this.lblOrderValue2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblOrderValue2.Location = new System.Drawing.Point(69, 65);

    this.lblOrderValue2.Name = "lblOrderValue2";

    this.lblOrderValue2.Size = new System.Drawing.Size(86, 14);

    //

    // lblPrice2

    //

    this.lblPrice2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblPrice2.Location = new System.Drawing.Point(35, 49);

    this.lblPrice2.Name = "lblPrice2";

    this.lblPrice2.Size = new System.Drawing.Size(86, 14);

    //

    // lblItemHeader

    //

    this.lblItemHeader.Font = new System.Drawing.Font("Tahoma", 8.5F, System.Drawing.FontStyle.Bold);

    this.lblItemHeader.Location = new System.Drawing.Point(3, 32);

    this.lblItemHeader.Name = "lblItemHeader";

    this.lblItemHeader.Size = new System.Drawing.Size(234, 14);

    this.lblItemHeader.Text = "No Item Selected";

    //

    // lblOrderValue

    //

    this.lblOrderValue.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblOrderValue.Location = new System.Drawing.Point(3, 65);

    this.lblOrderValue.Name = "lblOrderValue";

    this.lblOrderValue.Size = new System.Drawing.Size(68, 14);

    this.lblOrderValue.Text = "Order Value:";

    //

    // lblInventoryValue

    //

    this.lblInventoryValue.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblInventoryValue.Location = new System.Drawing.Point(3, 80);

    this.lblInventoryValue.Name = "lblInventoryValue";

    this.lblInventoryValue.Size = new System.Drawing.Size(87, 14);

    this.lblInventoryValue.Text = "Inventory Value:";

    //

    // lblPrice

    //

    this.lblPrice.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblPrice.Location = new System.Drawing.Point(3, 49);

    this.lblPrice.Name = "lblPrice";

    this.lblPrice.Size = new System.Drawing.Size(32, 14);

    this.lblPrice.Text = "Price:";

    //

    // lblUnits

    //

    this.lblUnits.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblUnits.Location = new System.Drawing.Point(127, 49);

    this.lblUnits.Name = "lblUnits";

    this.lblUnits.Size = new System.Drawing.Size(109, 14);

    this.lblUnits.TextAlign = System.Drawing.ContentAlignment.TopRight;

    //

    // lblPackSize

    //

    this.lblPackSize.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular);

    this.lblPackSize.Location = new System.Drawing.Point(181, 82);

    this.lblPackSize.Name = "lblPackSize";

    this.lblPackSize.Size = new System.Drawing.Size(55, 14);

    this.lblPackSize.TextAlign = System.Drawing.ContentAlignment.TopRight;

    //

    // frmMainq

    //

    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;

    this.ClientSize = new System.Drawing.Size(240, 268);

    this.Controls.Add(this.lblPackSize);

    this.Controls.Add(this.lblUnits);

    this.Controls.Add(this.lblInventoryValue2);

    this.Controls.Add(this.lblOrderValue2);

    this.Controls.Add(this.lblPrice2);

    this.Controls.Add(this.lblItemHeader);

    this.Controls.Add(this.lblOrderValue);

    this.Controls.Add(this.lblInventoryValue);

    this.Controls.Add(this.lblPrice);

    this.Controls.Add(this.txtEdit);

    this.Controls.Add(this.grid);

    this.Controls.Add(this.pnlHeader);

    this.Menu = this.mainMenu1;

    this.MinimizeBox = false;

    this.Name = "frmMainq";

    this.Text = "RIO";

    this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);

    this.Load += new System.EventHandler(this.frmMain_Load);

    this.pnlHeader.ResumeLayout(false);

    this.ResumeLayout(false);

    }

    #endregion

    #region Main

    /// <summary>

    /// The main entry point for the application.

    /// </summary>

    static void Main()

    {

    Application.Run(new frmMainq());

    }

    #endregion

    #region Form load

    private void frmMain_Load(object sender, System.EventArgs e)

    {

    Cursor.Current = Cursors.WaitCursor;

    // Populate Account Locations Menu

    PopulateAccountLocationsMenu();

    #region Set Labels and Menu Controls Text Properties

    strAccountName = data.LoadAccountName().ToString();

    lblAccountName.Text = strAccountName;

    miAccountName.Text = strAccountName;

    lblPrice2.Text = "$0.00";

    lblOrderValue2.Text = "$0.00";

    lblInventoryValue2.Text = "$0.00";

    #endregion

    // Get the grid scrollbars

    vsb = (VScrollBar)grid.GetType().GetField("m_sbVert", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance).GetValue(grid);

    hsb = (HScrollBar)grid.GetType().GetField("m_sbHorz", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance).GetValue(grid);

    Cursor.Current = Cursors.Default;

    }

    #endregion

    #region Populate Account Locations Menu

    private void PopulateAccountLocationsMenu()

    {

    MenuItem mainthreadNode = new MenuItem();

    mainthreadNode.Text = "All Items";

    miAccountName.MenuItems.Add(mainthreadNode);

    mainthreadNode.Click += new EventHandler(mi_Click);

    SqlCeDataReader dr = null;

    try

    {

    dr = data.LoadAccountLocations();

    while (dr.Read())

    {

    MenuItem threadNode = new MenuItem();

    threadNode.Text = dr["LocationName"].ToString();

    miAccountName.MenuItems.Add(threadNode);

    threadNode.Click += new EventHandler(mi_Click);

    }

    }

    catch (SqlCeException ex)

    {

    MessageBox.Show("Could not load Location Menu Data: " +

    ex.Message + ")!", "RIO Data Load Error");

    }

    finally

    {

    if (dr != null)

    {

    dr.Close();

    }

    }

    }

    #endregion

    #region Handle Menu Click Events

    //Handle Locations Menu Click Event

    private void mi_Click(object sender, EventArgs e)

    {

    strAccountName = data.LoadAccountName();

    MenuItem mi = (MenuItem)sender;

    Cursor.Current = Cursors.WaitCursor;

    lblAccountName.Text = strAccountName + " - " + mi.Text;

    // Style the layout of Projects in the DataGrid

    UtilGUI.AddCustomDataTableStyle(grid, 3);

    if (mi.Text == "All Items")

    {

    dlgRes = MessageBox.Show("Loading the 'All Items' category may take several minutes. Continue ", "Confirm Load 'All Items'", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    if (dlgRes == DialogResult.Yes)

    {

    // Load Inventory DataSet

    ds = data.LoadInventory("", "MobileInventory", "1", "");

    grid.DataSource = ds.Tables["MobileInventory"];

    }

    }

    else

    {

    // Load Inventory DataSet

    ds = data.LoadInventory(mi.Text, "MobileInventory", "1", "");

    grid.DataSource = ds.Tables["MobileInventory"];

    }

    grid.Visible = true;

    Cursor.Current = Cursors.Default;

    }

    //Handle RIO Exit Menu Click Event

    private void miExitRIO_Click_1(object sender, EventArgs e)

    {

    // The user wants to exit the application. Confirm - then Close everything down.

    dlgRes = MessageBox.Show("Are you sure you want to exit RIO ", "Confirm RIO Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    if (dlgRes == DialogResult.Yes)

    {

    GenerateXML();

    Application.Exit();

    this.Focus();

    }

    }

    //Generate XML from SQLCe DataSets

    private void miXML_Click(object sender, EventArgs e)

    {

    GenerateXML();

    }

    //Generate XML On-Demand

    private void GenerateXML()

    {

    dlgRes = MessageBox.Show("Generating the XML files may take several minutes. Continue ", "Confirm XML Generaton", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    if (dlgRes == DialogResult.Yes)

    {

    try

    {

    Cursor.Current = Cursors.WaitCursor;

    data.GenerateXML("MobileInventory").WriteXml(appPath + @"\\DATA\\MobileInventory.xml");

    data.GenerateXML("MobileAccounts").WriteXml(appPath + @"\\DATA\\MobileAccounts.xml");

    data.GenerateXML("MobileLocations").WriteXml(appPath + @"\\DATA\\MobileLocations.xml");

    dlgRes = MessageBox.Show("The XML files have been successfully generated.", "XML Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    catch (Exception ex)

    {

    dlgRes = MessageBox.Show("An error occured while generating the XML files: " + ex.Message.ToString(), "XML Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    finally

    {

    Cursor.Current = Cursors.Default;

    }

    }

    }

    //Items with Pars

    private void miItemsWithPars_Click(object sender, EventArgs e)

    {

    // Load Inventory DataSet

    Cursor.Current = Cursors.WaitCursor;

    DataSet ds = new DataSet();

    try

    {

    ds = data.LoadInventory("", "MobileInventory", "2", "");

    grid.DataSource = ds.Tables[0];

    grid.Visible = true;

    }

    finally

    {

    Cursor.Current = Cursors.Default;

    }

    }

    //Uninventoried Items

    private void miUnInvItems_Click(object sender, EventArgs e)

    {

    // Load Inventory DataSet

    Cursor.Current = Cursors.WaitCursor;

    string strDate = DateTime.Now.ToShortDateString();

    DataSet ds = new DataSet();

    try

    {

    ds = data.LoadInventory("", "MobileInventory", "3", strDate);

    grid.DataSource = ds.Tables[0];

    grid.Visible = true;

    }

    finally

    {

    vsb.Enabled = true;

    Cursor.Current = Cursors.Default;

    }

    }

    //GUI Mode Change (Inventory, Order, Both)

    private void Mode_Change(object sender, EventArgs e)

    {

    //Check for filter condition

    MenuItem mi = (MenuItem)sender;

    if (mi.Text.ToString() == "Inventory")

    {

    //if (grid.TableStyles["MobileInventory"].GridColumnStyles.Contains("OrderQuantity"))

    //{

    UtilGUI.AddCustomDataTableStyle(grid, 2);

    // Update MobileSettings Mode

    data.UpdateMobileSettingsData("Inventory");

    //}

    }

    else if (mi.Text.ToString() == "Order")

    {

    //if (grid.TableStyles["MobileInventory"].GridColumnStyles.Contains("QuantityOnHand"))

    //{

    UtilGUI.AddCustomDataTableStyle(grid, 1);

    // Update MobileSettings Mode

    data.UpdateMobileSettingsData("Order");

    //}

    }

    else

    {

    UtilGUI.AddCustomDataTableStyle(grid, 3);

    }

    vsb.Enabled = true;

    }

    #endregion

    #region Form closing

    private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)

    {

    // The user wants to exit the application. Confirm - then Close everything down.

    dlgRes = MessageBox.Show("Are you sure you want to exit RIO ", "Confirm RIO Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    if (dlgRes == DialogResult.Yes)

    {

    try

    {

    Cursor.Current = Cursors.WaitCursor;

    data.GenerateXML("MobileInventory").WriteXml(appPath + @"\\DATA\\MobileInventory.xml");

    data.GenerateXML("MobileAccounts").WriteXml(appPath + @"\\DATA\\MobileAccounts.xml");

    data.GenerateXML("MobileLocations").WriteXml(appPath + @"\\DATA\\MobileLocations.xml");

    dlgRes = MessageBox.Show("The XML files have been successfully generated.", "XML Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    catch (Exception ex)

    {

    dlgRes = MessageBox.Show("An error occured while generating the XML files: " + ex.Message.ToString(), "XML Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    finally

    {

    Cursor.Current = Cursors.Default;

    Application.Exit();

    this.Focus();

    }

    }

    }

    #endregion

    #region Grid handling

    // Helper function for setting grid back color.

    void SetGridBackColor(DataGrid dg, Color color)

    {

    object oRenderer = typeof(DataGrid).GetField("m_renderer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(dg);

    oRenderer.GetType().GetField("m_brushEmptyBack", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(oRenderer, new SolidBrush(color));

    }

    // Sort grid by column

    void SortGrid(int col)

    {

    // If a table was used as datasource, switch to its default dataview to avoid changing table data

    if (grid.DataSource is DataTable)

    grid.DataSource = (grid.DataSource as DataTable).DefaultView;

    // Get grid's dataview

    DataView vw = (DataView)grid.DataSource;

    string sort = vw.Table.Columns[col].ColumnName;

    // If dataview is already sorted by that column, change the sort order

    if (vw.Sort.StartsWith(sort))

    {

    if (vw.Sort.EndsWith("ASC"))

    vw.Sort = sort + " DESC";

    else

    vw.Sort = sort + " ASC";

    }

    // otherwise sort using specified column ascending

    else

    {

    vw.Sort = sort + " ASC";

    }

    }

    // Little trick to make sure the grid row is visible

    // Since we are going to pop automatically SIP panel to allow text entry, it might hide

    // our edit control. We are going to scroll grid first to make sure that current cell is

    // visible

    void EnsureRowVisible(DataGrid grd, int Row)

    {

    // Obtain first and last visible rows via reflection

    int FirstVisibleRow = (int)grd.GetType().GetField("m_irowVisibleFirst", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance).GetValue(grid);

    int LastVisibleRow = (int)grd.GetType().GetField("m_irowVisibleLast", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance).GetValue(grid);

    // If our row is outside visible range, scroll to it

    if (Row < FirstVisibleRow || Row > LastVisibleRow)

    {

    // Grid's vertical scrollbar has step one and Maximum set to grid's number of rows

    // This means that setting its value to a particular row number either brings that row to

    // the top of the grid, or at least makes sure it is visible

    // This could be somewhat modified to intelligently calculate to which row one needs to scroll

    // minimizing the amount of scrolling

    VScrollBar vsb = (VScrollBar)grd.GetType().GetField("m_sbVert", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance).GetValue(grid);

    vsb.Value = Row;

    }

    }

    #endregion

    // Grid's onclick handler. Performs most of the work

    private void grid_Click(object sender, System.EventArgs e)

    {

    // Get currently selected cell

    DataGridCell currentCell = grid.CurrentCell;

    grid.Select(grid.CurrentRowIndex);

    // Set Item Detal Labels Based Upon Selected Row

    DataRow dr = ds.Tables[0].Rows[grid.CurrentRowIndex];

    lblPrice2.Text = String.Format("{0:c}", double.Parse(dr["Price"].ToString())) + " per " + dr["OrderUnit"].ToString();

    lblItemHeader.Text = dr["ProviderName"].ToString() + " - " + dr["ItemNumber"].ToString() + " - " + dr["Description"].ToString();

    lblUnits.Text = dr["InventoryUnitsPerOrderUnit"].ToString() + " " + dr["InventoryUnit"].ToString() + "(s) per " + dr["OrderUnit"].ToString();

    lblOrderValue2.Text = String.Format("{0:c}", double.Parse(dr["OrderQuantity"].ToString()) * double.Parse((dr["Price"].ToString())));

    lblPackSize.Text = dr["PackSize"].ToString();

    // Get click event position (screen) and convert to grid position

    Point pt = grid.PointToClient(Control.MousePosition);

    // Get information about click position (type, row/col)

    DataGrid.HitTestInfo hti = grid.HitTest(pt.X, pt.Y);

    // If click was on the header area and we were not in edit mode, re-sort grid

    if (hti.Type == DataGrid.HitTestType.ColumnHeader && !bEditing)

    {

    SortGrid(hti.Column);

    }

    // If we are not in editing mode and currentCell is the one clicked onto, edit its contents

    if (!bEditing && hti.Row == currentCell.RowNumber && hti.Column == currentCell.ColumnNumber)

    {

    // Remember scrollbar states

    vsbEnabled = vsb.Enabled;

    hsbEnabled = hsb.Enabled;

    editColumn = GetInventoryMode();

    // Edit with TextBox

    //if (currentCell.ColumnNumber == editColumn) // Ord column

    //{

    // Show input panel

    sip.Enabled = true;

    // Let it pop up

    Application.DoEvents();

    // Make sure the cell we want to edit is visible

    EnsureRowVisible(grid, currentCell.RowNumber);

    // Resize and reposition TextBox to match current cell bounds

    Rectangle rc = grid.GetCellBounds(currentCell.RowNumber, editColumn);

    txtEdit.Bounds = this.RectangleToClient(grid.RectangleToScreen(rc));

    // Bring the focus to it

    txtEdit.SelectAll();

    txtEdit.Focus();

    ////Adjust its value to match current cell value

    //Adjust its value to null - clear existing cell value prior to manual update/override

    txtEdit.Text = "";//grid[currentCell.RowNumber, currentCell.ColumnNumber].ToString();

    // Finally, show the textBox

    txtEdit.Visible = true;

    //}

    // Hide both scroll bars to avoid moving the grid cells around inadvertently while editing

    vsb.Enabled = false;

    hsb.Enabled = false;

    bEditing = true;

    }

    else

    {

    // We are done with editing. Hide editing controls. Restore scrollbars if needed

    txtEdit.Visible = false;

    //vsb.Enabled = vsbEnabled;

    vsb.Enabled = true;

    hsb.Enabled = hsbEnabled;

    bEditing = false;

    sip.Enabled = false;

    }

    }

    // When text in the edit control is modified, update the grid.

    private void txtEdit_TextChanged(object sender, System.EventArgs e)

    {

    //Update grid

    if (!bEditing)

    {

    vsb.Enabled = true;

    sip.Enabled = false;

    return;

    }

    grid[grid.CurrentCell.RowNumber, 0] = txtEdit.Text;

    }

    private int GetInventoryMode()

    {

    if (data.GetInventoryMode().ToString() == "Inventory" &&

    grid.TableStyles["MobileInventory"].GridColumnStyles.Contains("QuantityOnHand") &&

    grid.TableStyles["MobileInventory"].GridColumnStyles.Contains("OrderQuantity"))

    {

    editColumn = 1;

    }

    else

    {

    editColumn = 0;

    }

    return editColumn;

    }

    // When input panel pops up, recalculate and shrink grid to make sure it is not obscured by input panel

    private void sip_EnabledChanged(object sender, System.EventArgs e)

    {

    grid.Height = Math.Min(this.RectangleToClient(sip.VisibleDesktop).Bottom, this.Bottom - SystemInformation.MenuHeight) - grid.Top;

    if (bEditing)

    {

    // Changing grid dimensions reenables scrollbars, which makes it possible for user

    // to scroll the grid under edit control after the sip state is changed.

    // To avoid this we want to explicitly disable scrollbars again

    vsbEnabled = vsb.Enabled;

    hsbEnabled = hsb.Enabled;

    vsb.Enabled = false;

    hsb.Enabled = false;

    }

    }

    private void menuItem3_Click(object sender, EventArgs e)

    {

    dlgRes = MessageBox.Show("Refreshing the XML files may take several minutes. Continue ", "Confirm XML Refresh", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

    if (dlgRes == DialogResult.Yes)

    {

    try

    {

    Cursor.Current = Cursors.WaitCursor;

    data.RefreshDataFromXML();

    dlgRes = MessageBox.Show("The data from the desktop has been successfully imported to the mobile device.", "Data Import Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    catch (Exception ex)

    {

    dlgRes = MessageBox.Show("An error occured while importing the data from the desktop to the mobile device: " + ex.Message.ToString(), "Data Import Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

    }

    finally

    {

    Cursor.Current = Cursors.Default;

    }

    }

    }

    private Label lblUnits;

    private Label lblPackSize;

    }

    }


  • Namtab

    Re: DG CurrentCell.ColumnNumber - HELP!!

  • Morris71

    It is blowing up at the following line:

    grid[currentCell.RowNumber, 0] = txtEdit.Text;

    Will post the full code in a few minutes -


  • DG CurrentCell.ColumnNumber - HELP!!