Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all 2535 articles
Browse latest View live

StackOverflowException sorting DataGridView with non-Visible rows.

$
0
0
Very simple project - create a C# Windows Forms application. Add one DataGridView to the form, not bound to any data source. Add one column.
In the form initiator code, add some rows, and hide some:
public Form1()

        {

            InitializeComponent();

            dataGridView1.Rows.Add("A1");

            dataGridView1.Rows.Add("A2");

            dataGridView1.Rows.Add("A3");//            dataGridView1.Rows.Add("b1");//            dataGridView1.Rows.Add("b2");//            dataGridView1.Rows.Add("b3");//            dataGridView1.Rows.Add("c1");//            dataGridView1.Rows.Add("c2");

            dataGridView1.Rows[0].Visible = false;

            dataGridView1.Rows[1].Visible = false;//            dataGridView1.Rows[2].Visible = false;//            dataGridView1.Rows[7].Visible = false;//            dataGridView1.Rows[6].Visible = false;

        }

The commented lines can be uncommented if you want to play with this problem some, but this code should be sufficient as it stands.

Now, run the program, and sort the column a few times.

I get:

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll

The call stack looks like this (the last row repeats for ever, as you'd expect with a stack overflow exception)

 System.Windows.Forms.dll!System.Windows.Forms.PropertyStore.LocateObjectEntry(short entryKey = 92, out int index = 0) + 0x1d bytes 
  System.Windows.Forms.dll!System.Windows.Forms.PropertyStore.GetObject(int key, out bool found = false) + 0x37 bytes 
  System.Windows.Forms.dll!System.Windows.Forms.DataGridViewRow.AccessibilityObject.get() + 0x3a bytes 
  System.Windows.Forms.dll!System.Windows.Forms.DataGridView.DataGridViewAccessibleObject.GetChild(int index) + 0xa3 bytes 
  System.Windows.Forms.dll!System.Windows.Forms.DataGridViewRow.DataGridViewRowAccessibleObject.Bounds.get() + 0x16f bytes 
  System.Windows.Forms.dll!System.Windows.Forms.DataGridViewRow.DataGridViewRowAccessibleObject.Bounds.get() + 0x179 bytes 
  System.Windows.Forms.dll!System.Windows.Forms.DataGridViewRow.DataGridViewRowAccessibleObject.Bounds.get() + 0x179 bytes 

I am seeing this error occasionally in real code that I'm trying to make work - this sample is deliberately small to make sure that it's clear that I'm not doing anything special.

Has anyone else encountered this issue, and is there a solution? I've searched as many places as I can think of, but not yet found a solution.

Alun.
~~~~

PLEASE help Datagridview printing function

$
0
0

Greetings,

In my windows application have 2 DGV. One is showing data that is being fetched through queries from sql server management studio and as this GVD is bound, I'm showing the sum of columns in another DGV placed beneath it. After that I'm print them both one after the other. The sum is only needed for printing purposes. 

I'm using the following link as reference and i've managed to place one datagridview after the other 

"http://www.codeproject.com/Articles/28046/Printing-of-DataGridView"

I can't post the picture as my account is still not verified but what I have achieved for far it to place one DGV next to another.

I can't fully comprehend the code on that link. Can you please tell me how I put my second DGV below the first one and hide it's header names

Thanks A LOT.

Any kind of help will be fully appreciated.

how to control the installation of another setup file in windows application

$
0
0

I want to automate the process which tries to install another setup.exe file while installation there are different function like selecting the buttons like "Next" selecting checkboxes and destnation path selection can someone help me on how to control buttons checkbox selection  and setting destination path of installation file using c#

thanks

Get the first value (first row) in a certain column

$
0
0

I want to get the first value (first row) in a certain column of a DataGridView. How do I do that?

Null Reference Exception when adding column to Column Collection

$
0
0

I am adding column to the column collection of a data table.  The data table is the data source of a data grid view.  AutoGenerateColumns is set to false on the DataGridView.

 

I am displaying a context menu in the MouseUp event of the datagridview.  The column is then added in the event handler on item in the context menu.

 

When adding the column I get the following exception.  Any help would be appreciated in how to preven the exception. 

 

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="System.Windows.Forms"
  StackTrace:
       at System.Windows.Forms.DataGridView.ComputeVisibleColumns()
       at System.Windows.Forms.DataGridView.LayoutScrollBars()
       at System.Windows.Forms.DataGridView.ComputeLayout()
       at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl)
       at System.Windows.Forms.DataGridView.OnColumnWidthChanged(DataGridViewColumnEventArgs e)
       at System.Windows.Forms.DataGridView.OnBandThicknessChanged(DataGridViewBand dataGridViewBand)
       at System.Windows.Forms.DataGridViewBand.set_Thickness(Int32 value)
       at System.Windows.Forms.DataGridView.EndColumnResize(MouseEventArgs e)
       at System.Windows.Forms.DataGridView.OnMouseUp(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.DataGridView.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Systech.AdvProdConfig.Program.Main(String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

Thank you.

datagridview usedrcontrol cell Issue

$
0
0

i created usercontrol ( textbox and Combobox) and added to datagridview first row ,

if i clicked in Combobox cell 0 then go to cell 1 then comeback to cell 0 

the datagridview.currentcell.columnindex stayed in cell 1 

i mean the cellclick fires only first time clicking the cell . if i clicked again to change the value of combobox it not fire again !!

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

 Type CurrentCellDataType = dataGridView1.Columns[e.ColumnIndex].ValueType;
                    if (e.RowIndex == 0)
                {
                    if ((CurrentCellDataType.Name != "DateTime" &&
                         CurrentCellDataType.Name != "DateTime2" &&
                         CurrentCellDataType.Name != "Date"))
                    {
                    
                        txbComboControl = new TextWithComboControl();
                        txbComboControl.RightToLeft = this.RightToLeft;
                        txbComboControl.Visible = false;
                        dataGridView1.Controls.Add(txbComboControl);
                        txbComboControl.textbox1.KeyPress += new KeyPressEventHandler(txbComboControl_OnKeyPress);

                        Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                        txbComboControl.Location = rect.Location;
                        txbComboControl.Size = rect.Size;
                        txbComboControl.FilterText = this.dataGridView1.CurrentCell.Value.ToString();
                        if (OperationValue != "")
                            txbComboControl.SelectedOperation = OperationValue;

                        txbComboControl.renderControl();
                        txbComboControl.Visible = true;

                        txbComboControl.textbox1.TextChanged += new EventHandler(txbComboControl_OnTextChange);
                        txbComboControl.OperationBox.SelectedValueChanged += new EventHandler(txbComboControl_OnCmboTextChange);
                    }

}

How do I hide first column in every DataGridView using a CheckBox?

$
0
0

How do I hide the first column for all the DataGridViews in the tabs?

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            tabControl1.TabPages.Clear();
            createGridViews();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dgwDynamic.Columns["Column1"].Visible = false;
        }

        DataGridView dgwDynamic;
        private void createGridViews()
        {
            int pageNumber = 0;
            for (int i = 0; i < 3; i++)
            {
                /* Dynamic DataGridView */
                dgwDynamic = new DataGridView();
                dgwDynamic.Name = "DataGridView" + i.ToString();
                dgwDynamic.ScrollBars = ScrollBars.Both;
                dgwDynamic.Dock = DockStyle.Fill;

                /* Dynamic TabPage */
                TabPage tpDynamic = new TabPage();
                pageNumber = i + 1;
                tpDynamic.Name = "tabPage" + pageNumber.ToString();

                string tabName = "TabPage" + pageNumber.ToString();

                tpDynamic.Text = tabName;

                tpDynamic.TabIndex = i;
                // One newGridView per newTabPage
                tpDynamic.Controls.Add(dgwDynamic); // Add Dynamic DataGridView to Dynamic TabPage
                tabControl1.Controls.Add(tpDynamic); // Add Dynamic TabPage to TabControl
                dgwDynamic.DataSource = GetTable(); // Add DataTable to Dynamic DataGridView

            }//End for loop
        }

        private static DataTable table;
        static DataTable GetTable()
        {
            // Here we create a DataTable with four columns.
            table = new DataTable();
            table.Columns.Add("Column1", typeof(string));
            table.Columns.Add("Column2", typeof(string));
            table.Columns.Add("Column3", typeof(string));

            // Here we add five DataRows.
            table.Rows.Add("Col1_Row1", "Col2_Row1", "Col3_Row1");
            table.Rows.Add("Col1_Row2", "Col2_Row2", "Col3_Row2");
            table.Rows.Add("Col1_Row3", "Col2_Row3", "Col3_Row3");
            table.AcceptChanges();
            return table;
        }
    }
I want to hide the first column for every DGW with one click? By the way, how do I also display the columns again when uncheck the CheckBox? Or maybe it would be more logical to hide the columns from the beginning and then check the CheckBox to have them displayed (so true=show columns, false=hide columns).



How to bind the the datatable datasource to a predefined combobox column of the datagridview from the sql

$
0
0

I have  4 column in datagridview, Item, Qty,Rate,Total. I am creating the dropdown list for the columnItem column from the following sql

Select A.Code, A.Description From kmProduct A Where  A.Hidden = 'F'Order ByA.Code

My code is as follows

DataGridViewComboBoxColumn ColProduct = new DataGridViewComboBoxColumn();
            ColProduct.DataPropertyName = "Code";
            ColProduct.HeaderText = "Description";
            kmInvoice objKmInvoice = new kmInvoice();
            DataTable t = new DataTable();
            t = objKmInvoice.GetProductList();
            ColProduct.DataSource = t;
            ColProduct.ValueMember = "Code";
            ColProduct.DisplayMember = "Description";
            dataGridViewInvoice.Columns.Add(ColProduct);

After running the application, it create a new column with the name of Description. How I can create the dropdown  to the existing column 'Item' Please any help very appreciate.

Regards

Pol


polachan


Drag n drop fails - Object reference not set to an instance of an object

$
0
0

I did follow a Drag N Drop tutorial on YouTube, did exactly the same thing but I get the error:

"Object reference not set to an instance of an object".

The difference would be that I do create the DataGridView in code behind. Also there's several of them. One in each tab.

How do I adjust my code to make it work?

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            tabControl1.TabPages.Clear();
            createGridViews();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dgwDynamic.Columns["Column1"].Visible = false;
        }

        DataGridView dgwDynamic;
        private void createGridViews()
        {
            int pageNumber = 0;
            for (int i = 0; i < 3; i++)
            {
                //Populate DataGridView.

                /* Dynamic DataGridView */
                dgwDynamic = new DataGridView();
                dgwDynamic.Name = "DataGridView" + i.ToString();
                dgwDynamic.ScrollBars = ScrollBars.Both;
                dgwDynamic.Dock = DockStyle.Fill;

                /* Dynamic TabPage */
                TabPage tpDynamic = new TabPage();
                pageNumber = i + 1;
                tpDynamic.Name = "tabPage" + pageNumber.ToString();

                string tabName = "TabPage" + pageNumber.ToString();

                tpDynamic.Text = tabName;

                tpDynamic.TabIndex = i;
                // One newGridView per newTabPage
                tpDynamic.Controls.Add(dgwDynamic); // Add Dynamic DataGridView to Dynamic TabPage
                tabControl1.Controls.Add(tpDynamic); // Add Dynamic TabPage to TabControl
                dgwDynamic.DataSource = GetTable(); // Add DataTable to Dynamic DataGridView
                /* Drag N Drop EventHandler */
                dgwDynamic.CellMouseDown += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dgwDynamic_CellMouseDown);

            }//End for loop
        }

        private static DataTable table;
        static DataTable GetTable()
        {
            // Here we create a DataTable with four columns.
            table = new DataTable();
            table.Columns.Add("Column1", typeof(string));
            table.Columns.Add("Column2", typeof(string));
            table.Columns.Add("Column3", typeof(string));


            // Here we add five DataRows.
            table.Rows.Add("Col1_Row1", "Col2_Row1", "Col3_Row1");
            table.Rows.Add("Col1_Row2", "Col2_Row2", "Col3_Row2");
            table.Rows.Add("Col1_Row3", "Col2_Row3", "Col3_Row3");
            table.AcceptChanges();
            return table;
        }

        private void dgwDynamic_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //To Copy the data selected
            dgwDynamic.DoDragDrop(dgwDynamic.CurrentCell.Value.ToString(), DragDropEffects.Copy);
            // ERROR: Object reference not set to an instance of an object
        }

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            listBox1.Items.Add(e.Data.GetData(DataFormats.Text));
        }

    }

Checkbox in the first row of datagrivew does not respond to click (does not check and un check)

$
0
0
I have a winforms window with three tabs. All the three tabs have datagridviews. In first 2 tabs the datgridview is in virtual mode. While the last tabs datagridview is databound. All these DataGrids have checkbox column(column0). On 1 machine the checkbox in the row0 does not get checked or unchecked. Sorting the datagridview does not help either even though there is new data in row0 the checkbox does not respond. This happens in all 3 datagridviews.

It appears checkbox is not changing state upon mouse click however pressing space on the checkbox of row0 does check it.

Both the machines run win 7, similar hardware. The application uses .NET 3.5. I am not sure what else to look for!!

For the virtual mode grids the events that are being handled are CellValuePushed, CellMouseDown, CurrentCellDirtyStateChanged, CellValueNeeded,CellValueChanged,CellFormatting. 

While in databound grid has CellValueChanged & CellFormatting events handled.


Cannot understand what is the issue! help

Speech in C# Error

$
0
0

I have a speech program with an error...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {

        SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();

        public Form1()
        {
            InitializeComponent();
            recEngine.RecognizeAsync(RecognizeMode.Multiple);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button2.Enabled = true;
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Choices commands = new Choices();
            commands.Add(new string[] { "say hello", "print my name" });
            GrammarBuilder gBuilder = new GrammarBuilder();
            gBuilder.Append(commands);
            Grammar grammar = new Grammar(gBuilder);

            recEngine.LoadGrammarAsync(grammar);
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechRecognized += recEngine_SpeechRecognized;
            gBuilder.Culture = new System.Globalization.CultureInfo("en-GB");//en-GB
        }

        private void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                case "say hello":
                    MessageBox.Show("Hello Ganesh");
                    break;

                case "print my name":
                    richTextBox1.Text += "\nGanesh";
                    break;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsyncStop();
            button2.Enabled = false;
        }
    }
}

Design

Error


How to modify the DataGridViewer selector

$
0
0

Hi,

I would like to reduce the first column of the DataGridViewer on a Window form. Can someone let me know what property is this?

A screen-shot is attached.

Thanks

blank page when printing datagridview

$
0
0

I'm trying to print a datagridview, but only some columns.

PrintpreviewDialog shows the document but when I'm trying to print it print only the header of my table and and nothing else

 private void print_Click(object sender, EventArgs e)
        {
            PrintDocument doc = new PrintDocument();
            doc.PrintPage += this.Doc_PrintPage;

            PrintDialog dlgSettings = new PrintDialog();
            dlgSettings.Document = doc;
             PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.SetBounds(200, 100, 500, 600);
            printPreviewDialog.Document = doc;
            printPreviewDialog.ShowDialog();
         }
        int i = 0;
        private void Doc_PrintPage(object sender, PrintPageEventArgs e)
        {
            int height = 110;
            int width = 0;
            int x = 80;
            int y2 = 40;
            Pen p = new Pen(Brushes.Black);
            float y = e.MarginBounds.Top + 50;
            StringFormat stringFormat = new StringFormat();
            stringFormat.LineAlignment = StringAlignment.Center;
            StringFormat stringFormat1 = new StringFormat();
            stringFormat1.Alignment = StringAlignment.Center;
            stringFormat1.LineAlignment = StringAlignment.Center;

            e.Graphics.DrawString("DOCUMENTS, DATE: " + DateTime.Now.ToString("dd.MM.yyyy"), new Font("Arial", 12, FontStyle.Bold), Brushes.Black, x + 100, y - 100);
            Graphics g = e.Graphics;
            Font fontText = new Font("Times New Roman", 10, FontStyle.Bold);
            RectangleF rect11 = new RectangleF(x, y - 50, 130, 25);
            g.DrawString("NR", fontText, Brushes.Black, rect11, stringFormat1);
            g.DrawRectangle(Pens.Black, Rectangle.Round(rect11));
            RectangleF rect10 = new RectangleF(x, y - 25, 50, 25);
            g.DrawString("DATA", fontText, Brushes.Black, rect10, stringFormat1);
            g.DrawRectangle(Pens.Black, Rectangle.Round(rect10));
            RectangleF rect20 = new RectangleF(x + 50, y - 25, 80, 25);
            g.DrawString("WRITER", fontText, Brushes.Black, rect20, stringFormat1);
            g.DrawRectangle(Pens.Black, Rectangle.Round(rect20));
            RectangleF rect12 = new RectangleF(x + 130, y - 50, 330, 25);
            g.DrawString("PAGES", fontText, Brushes.Black, rect12, stringFormat1);
            g.DrawRectangle(Pens.Black, Rectangle.Round(rect12));
            RectangleF rect30 = new RectangleF(x + 130, y - 25, 200, 25);

            while (i < dataGridView2.Rows.Count)
            {
                if (height > 1000)
                {
                    height = 110;
                    e.HasMorePages = true;
                    return;
                }
                 height += dataGridView1.Rows[0].Height;
                height += 18;
                e.Graphics.DrawRectangle(p, new Rectangle(x, height, 50, y2));
                e.Graphics.DrawString(dataGridView2.Rows[i].Cells["NR"].FormattedValue.ToString(), dataGridView1.Font, Brushes.Black, new Rectangle(x, height, 50, y2));

                e.Graphics.DrawRectangle(p, new Rectangle(x + 50, height, 80, y2));
                e.Graphics.DrawString(dataGridView2.Rows[i].Cells["DATA"].FormattedValue.ToString(), dataGridView1.Font, Brushes.Black, new Rectangle(x + 50, height, 80, y2));

                e.Graphics.DrawRectangle(p, new Rectangle(x + 130, height, 200, y2));
                e.Graphics.DrawString(dataGridView2.Rows[i].Cells["WRITER"].FormattedValue.ToString(), dataGridView1.Font, Brushes.Black, new Rectangle(x + 130, height, 200, y2));

                e.Graphics.DrawRectangle(p, new Rectangle(x + 330, height, 50, y2));
                e.Graphics.DrawString(dataGridView2.Rows[i].Cells["PAGES"].FormattedValue.ToString(), dataGridView1.Font, Brushes.Black, new Rectangle(x + 330, height, 50, y2));

                e.Graphics.DrawRectangle(p, new Rectangle(x + 380, height, 80, y2));
                i++;
            }
        }
Help me please!

DataSet Bug

$
0
0
previously I have created one project with .mdf file failed to make display in Listbox...
but same I failed in Make changes in dataset..

code is below

Public Class Form1
    Private Sub ReportBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles ReportBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.ReportBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.StReportDataSet)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'StReportDataSet.Report' table. You can move, or remove it, as needed.
        Me.ReportTableAdapter.Fill(Me.StReportDataSet.Report)

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Me.ReportBindingSource.EndEdit()
        Me.ReportTableAdapter.Update(Me.StReportDataSet.Report)
    End Sub
End Class

I made form1 closing code  to save the changed data in data set. ..

Table pic

Dataset interface

After Run the program

I made changes by input 5 Row..and clicked save then close. .

Data is same as previous

Then how to do save and update the data?

How do I change text colour in DataGridView cell?

$
0
0

I have DataGridView and if a cell (in specific column) have a certain value it will change the background of the whole row (the same row where the value exists).

Now I would like to make two changes:

1. Instead of having backround set to yellow I only want the text to change, to red colour. I want to keep the default backround and only manipulate the text.

2. Then I only want to change the text in the cell where the condition is met. So in this case I want "Hello Word!" to be red.

This is the code:

public partial class Form1 : Form { public Form1() { InitializeComponent(); tabControl1.TabPages.Clear(); createGridViews(); } DataGridView dgwDynamic; private void createGridViews() { int pageNumber = 0; for (int i = 0; i < 3; i++) { //Populate DataGridView. /* Dynamic DataGridView */ dgwDynamic = new DataGridView(); dgwDynamic.Name = "DataGridView" + i.ToString(); dgwDynamic.ScrollBars = ScrollBars.Both; dgwDynamic.Dock = DockStyle.Fill; dgwDynamic.DataBindingComplete += dgwDynamic_DataBindingComplete; /* Dynamic TabPage */ TabPage tpDynamic = new TabPage(); pageNumber = i + 1; tpDynamic.Name = "tabPage" + pageNumber.ToString(); string tabName = "TabPage" + pageNumber.ToString(); tpDynamic.Text = tabName; tpDynamic.TabIndex = i; // One newGridView per newTabPage tpDynamic.Controls.Add(dgwDynamic); // Add Dynamic DataGridView to Dynamic TabPage tabControl1.Controls.Add(tpDynamic); // Add Dynamic TabPage to TabControl dgwDynamic.DataSource = GetTable(); // Add DataTable to Dynamic DataGridView }//End for loop } private static DataTable table; static DataTable GetTable() { // Here we create a DataTable with four columns. table = new DataTable(); table.Columns.Add("Column1", typeof(string)); table.Columns.Add("Column2", typeof(string)); table.Columns.Add("Column3", typeof(string)); // Here we add three DataRows. table.Rows.Add("Col1_Row1", "Col2_Row1", "Col3_Row1"); table.Rows.Add("Col1_Row2", "Hello World!", "Col3_Row2"); table.Rows.Add("Col1_Row3", "Col2_Row3", "Col3_Row3"); table.AcceptChanges(); return table; } private void dgwDynamic_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { List<String> myList = new List<String>(); myList.Add("ABC"); myList.Add("DEF"); myList.Add("Hello World!"); // Format Rows demo DataGridView dgw = (DataGridView)sender; if (dgw != null) { foreach (DataGridViewRow row in dgw.Rows) { //if new row skip, otherwise null reference exception if (row.IsNewRow) return; foreach (DataGridViewCell cell in row.Cells) { if (cell.ColumnIndex == 1) //Particular column index { if (myList.Contains(cell.Value.ToString())) { //IF CONDITION IS MET FOR THE CELL SET THE BACKGROUND OF THE ROW TO BE YELLOW row.DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;

//NEED TO CHANGE TEXT INSTEAD OF BACKGROUND AND ONLY THE PARTICULAR CELL THAT CONTAINS THE VALUE //Some code here to change the text colour in the cell...

} } } } } } }//End partial class


So how do I change my code to have the desired result?



DataGridView causing error

$
0
0
Private Sub UpdateGrid()
        Try

            If Me.DataGridView1.IsCurrentCellDirty = True Then
                Me.DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
                Me.BindingSource1.EndEdit()
            End If

            Dim myBuilder As SqlCommandBuilder = New SqlCommandBuilder(adapter)
            myBuilder.GetUpdateCommand()
            adapter.UpdateCommand = myBuilder.GetUpdateCommand()

            For Each row As DataRow In table.Rows
                If row.RowState = DataRowState.Modified Then
                    row("UserID") = USER.ID
                End If
            Next

            adapter.Update(table)


        Catch e As SqlException
            Debug.Print("SQL Err - " & e.ErrorCode)
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try

    End Sub

Visual Studio 2010 - VB.NET

My application is used in a manufacturing production environment.

One essential activity is controlled/changed by use of a DataGridView control.

It appears that after updating this control, somehow (on rare occasions) a blank space is being appended to one of the underlying columns in SQL server.  The code that loads and updates the control is attached.  the field affected is called sterileNo.  

Has anyone got any suggestions?  Would I be better to use code to explicitly update my database for each ro rather than using a BindingConrol?

Thanks

Private Sub SetDataGridView()
        Try
            ' Set up the DataGridView.
            With Me.DataGridView1

                .AutoGenerateColumns = True

                ' Set up the data source.
                BindingSource1.DataSource = _
                    GetData("SELECT * FROM sterilecontrol WHERE sterileno='" & _
                    Trim$(Me.txtSterileNo.Text) & "' AND steriledate='" & Me.dtpSterileDate.Text & "'")
                .DataSource = BindingSource1

                ' Automatically resize the visible rows.
                .AutoSizeRowsMode = _
                    DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders

                ' Set the DataGridView control's border.
                .BorderStyle = BorderStyle.Fixed3D

                ' Put the cells in edit mode when user enters them.
                .EditMode = DataGridViewEditMode.EditOnEnter
            End With
        Catch ex As SqlException
            MsgBox(ex.Message)
        End Try
    End Sub
<input id="238de6cd-29fe-44e1-a14e-6dce751b3fce_attachments" type="hidden" value="" />                
        
                
           
                         
              

IDataErrorInfo - DataGridView calls Error() but not item[] indexer

$
0
0

The item indexer never gets called so that the error icon won't ever get shown in the cell. Since the .Error() method gets called the row error icon does show. 

What is missing to enable the grid to call my indexer method show it will show the error?

In my form/user control i am setting up the grid:'

_radioItemsGrid.AutoGenerateColumns = false;

			_options.RadioButtons = new List<RadioButtonItem>();

			var bs = new BindingSource(_options.RadioButtons, null);
	        	_radioItemsGrid.DataSource = bs;

	        errorProvider1.DataSource = _radioItemsGrid.DataSource;


Here is my biz class

public class RadioButtonItem : IDataErrorInfo
	{
		public string Label
		{
			get { return _label; }
			set
			{
				if (_label != value)
				{
					_label = value;
					if(string.IsNullOrWhiteSpace(value))
						SetError(nameof(Label), "Label is required");
				}
			}
		}

		public string ModelExpression
		{
			get { return _modelExpression; }
			set
			{
				if (_modelExpression != value)
				{
					_modelExpression = value.Clean();
					if (string.IsNullOrWhiteSpace(value))
						SetError(nameof(ModelExpression), "Model Expression is required");
				}
			}
		}

		public string Error => _errors.Any() ? string.Join(Environment.NewLine, _errors.Select(e => e.Value).ToArray()) : "";

		private void SetError(string columnName, string errorMessage)
		{
			if(_errors.ContainsKey(columnName))
				_errors[columnName] = errorMessage;
			else
				_errors.Add(columnName, errorMessage);
		}

		private Dictionary<string, string> _errors = new Dictionary<string, string>();
		private string _label;
		private string _modelExpression;

		public string this[string columnName]
		{
			get
			{
				if (_errors.ContainsKey(columnName))
					return _errors[columnName];

				return string.Empty;
			}
		}

thanks!

Datagridview MaskedTextBox Can't Remove Value

$
0
0

I have a winforms app with SQL for the database.

I have added a masked textbox to my datagridview using 00/00/0000 as the mask. When I try to remove the date from the cell I get the following error when I try to leave the cell.

Name:  datagridviewmask.JPG
Views: 74
Size:  108.4 KB

I have used the following code to add the datagridview masked textbox to my winform app. Three classes MaskedEditColumn, MaskedEditCell, MaskedEditingControl. This code is far beyond my skills and I cannot figure out what I need to change to so the user can remove a date from the masked datagridview cell and have the cell empty.

The masked textbox is a nice way to make sure data is entered in the proper format.  Here is a way to place a maskedtextbox in the datagridview.

Public Class MaskedEditColumn
    Inherits DataGridViewColumn
    Public Sub New()
        MyBase.New(New MaskedEditCell())
    End Sub

    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)

            ' Ensure that the cell used for the template is a CalendarCell.
            If Not (value Is Nothing) AndAlso _
                Not value.GetType().IsAssignableFrom(GetType(MaskedEditCell)) _
                Then
                Throw New InvalidCastException("Must be a MaskedEditCell")
            End If
            MyBase.CellTemplate = value
        End Set
    End Property

    Private m_strMask As String
    Public Property Mask() As String
        Get
            Return m_strMask
        End Get
        Set(ByVal value As String)
            m_strMask = value
        End Set
    End Property

    Private m_tyValidatingType As Type
    Public Property ValidatingType() As Type
        Get
            Return m_tyValidatingType
        End Get
        Set(ByVal value As Type)
            m_tyValidatingType = value
        End Set
    End Property

    Private m_cPromptChar As Char = "_"c
    Public Property PromptChar() As Char
        Get
            Return m_cPromptChar
        End Get
        Set(ByVal value As Char)
            m_cPromptChar = value
        End Set
    End Property

    Private ReadOnly Property MaskedEditCellTemplate() As MaskedEditCell
        Get
            Return TryCast(Me.CellTemplate, MaskedEditCell)
        End Get
    End Property
End Class

Public Class MaskedEditCell
    Inherits DataGridViewTextBoxCell
    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
        ByVal initialFormattedValue As Object, _
        ByVal dataGridViewCellStyle As DataGridViewCellStyle)
        ' Set the value of the editing control to the current cell value.
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
            dataGridViewCellStyle)
        Dim mecol As MaskedEditColumn = DirectCast(OwningColumn, MaskedEditColumn)
        Dim ctl As MaskedEditingControl = _
            CType(DataGridView.EditingControl, MaskedEditingControl)
        Try
            ctl.Text = Me.Value.ToString
        Catch
            ctl.Text = ""
        End Try
        ctl.Mask = mecol.Mask
        ctl.PromptChar = mecol.PromptChar
        ctl.ValidatingType = mecol.ValidatingType
    End Sub

    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing contol that CalendarCell uses.
            Return GetType(MaskedEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that CalendarCell contains.
            Return GetType(String)
        End Get
    End Property

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            ' Use the current date and time as the default value.
            Return ""
        End Get
    End Property

    Protected Overrides Sub Paint(ByVal graphics As System.Drawing.Graphics, ByVal clipBounds As System.Drawing.Rectangle, ByVal cellBounds As System.Drawing.Rectangle, ByVal rowIndex As Integer, ByVal cellState As System.Windows.Forms.DataGridViewElementStates, ByVal value As Object, ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As System.Windows.Forms.DataGridViewCellStyle, ByVal advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, ByVal paintParts As System.Windows.Forms.DataGridViewPaintParts)
        MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
    End Sub
End Class

Class MaskedEditingControl
    Inherits MaskedTextBox
    Implements IDataGridViewEditingControl
    Private dataGridViewControl As DataGridView
    Private valueIsChanged As Boolean = False
    Private rowIndexNum As Integer
    Public Property EditingControlFormattedValue() As Object _
        Implements IDataGridViewEditingControl.EditingControlFormattedValue
        Get
            Return Me.Text
        End Get
        Set(ByVal value As Object)
            Me.Text = value.ToString
        End Set
    End Property

    Public Function EditingControlWantsInputKey(ByVal key As Keys, _
           ByVal dataGridViewWantsInputKey As Boolean) As Boolean _
           Implements IDataGridViewEditingControl.EditingControlWantsInputKey
        Return True
    End Function

    Public Function GetEditingControlFormattedValue(ByVal context _
        As DataGridViewDataErrorContexts) As Object _
        Implements IDataGridViewEditingControl.GetEditingControlFormattedValue
        Return Me.Text
    End Function

    Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As  _
        DataGridViewCellStyle) _
        Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl

        Me.Font = dataGridViewCellStyle.Font
        Me.ForeColor = dataGridViewCellStyle.ForeColor
        Me.BackColor = dataGridViewCellStyle.BackColor
    End Sub

    Public Property EditingControlRowIndex() As Integer _
        Implements IDataGridViewEditingControl.EditingControlRowIndex
        Get
            Return rowIndexNum
        End Get
        Set(ByVal value As Integer)
            rowIndexNum = value
        End Set
    End Property

    Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _
        Implements IDataGridViewEditingControl.PrepareEditingControlForEdit
        ' No preparation needs to be done.
    End Sub

    Public ReadOnly Property RepositionEditingControlOnValueChange() _
        As Boolean Implements _
        IDataGridViewEditingControl.RepositionEditingControlOnValueChange
        Get
            Return False
        End Get
    End Property

    Public Property EditingControlDataGridView() As DataGridView _
        Implements IDataGridViewEditingControl.EditingControlDataGridView
        Get
            Return dataGridViewControl
        End Get
        Set(ByVal value As DataGridView)
            dataGridViewControl = value
        End Set
    End Property

    Public Property EditingControlValueChanged() As Boolean _
        Implements IDataGridViewEditingControl.EditingControlValueChanged
        Get
            Return valueIsChanged
        End Get
        Set(ByVal value As Boolean)
            valueIsChanged = value
        End Set
    End Property
    Public ReadOnly Property EditingControlCursor() As Cursor _
        Implements IDataGridViewEditingControl.EditingPanelCursor
        Get
            Return MyBase.Cursor
        End Get
    End Property

    Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
        ' Notify the DataGridView that the contents of the cell have changed.
        valueIsChanged = True
        Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
        MyBase.OnTextChanged(e)
    End Sub
End Class

I realize that the slashes in my mask are making the system believe there is data in the field but I'm not sure how to override this value to tell it the cell is empty.  I have tried putting code on the CellLeave and the CellValidating events and nothing seems to work.  It could be because I'm not exactly sure how to override that mask though.  This has been driving me nuts and if you understand how to fix my problem your help would be much appreciated.

Thank you,
Stacy

how to check repeated value in Datagridview column Item

$
0
0

Hi

I have 4 column in the datagridview dgview1

Item    Rate          Vat                  Total

When I  give  duplicate item  in the datagridview dgview1, how can I validate with messagebox  and  to prevent the user to give duplicate  code

Please any help very appreciate

Pol


polachan

webBrowser1 control shows Empty popups

$
0
0

Hello,

I am using the webBrowser1 control.

I am navigating to a webpage and then I click on a link on that webpage which do produces a popupwindow in

the "real Windows Explorer browser". However this popup is completely blank/white. If I click on that link in the 

"real Windows Explorer browser" window, - then the popup shows as it should with text etc.

Why is the popup blank and empty?

I have tried to put this property to false and true with the same results:

webBrowser1.Navigate("http://someurl.com");

//I have tried both below
webBrowser1.ScriptErrorsSuppressed = false;
webBrowser1.ScriptErrorsSuppressed = true;

Viewing all 2535 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>