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

Datagridview Accept Current Edits when toolbar save button Clicked

$
0
0

Scenario:

I have a editable datagridview and a toolbar with a save button on the form.

Users are typing a value into the cell and clicking the save button. 

This results in the record not saving the typed value as they have not accepted the change by using the enter Key or changing their selection to an alternative row.

Is there a way to have the save button accept the change as if the enter button was pressed prior to the save button?


How to create template excel based on table columns order not forms control

$
0
0

Problem

I need to modify function GetFormFields to Get Order Of column on table selected .

meaning if i have table name items have four fields itemcode,itemname,itemtech,itemsize

it must create template excel based on tables column order according to four columns above

Current it working according to order of controls on form and this is wrong .

so that if itemcode have tab index 3 it will show as number 3 and i dont need that

i need to order as table created 

public static void CreateExcelTemplate(xForm frm)
    {
        try
        {
            if (frm.TableName == "") return;

            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook Book = null;
            Microsoft.Office.Interop.Excel._Worksheet Sheet = null;
            ExcelApp.Visible = false;
            Book = ExcelApp.Workbooks.Add("WorkBook");
            Sheet = Book.ActiveSheet;

            List<string> Columns = new List<string>();
            Dictionary<string, string> GlobalFields = SqlFactory.Queries.GetGlobalFieldsForTable(frm.TableName);
            foreach (KeyValuePair<string, string> keys in GlobalFields)
            {
                Columns.Add(keys.Key);
            }
            foreach (string s in frm.AnotherKeys.Keys)
            {
                Columns.Add(s);
            }
            GetFormFields(frm.Controls, ref Columns);

            String MaxColumn = ((String)(Convert.ToChar(Columns.Count / 26 + 64).ToString() + Convert.ToChar(Columns.Count % 26 + 64))).Replace('@', ' ').Trim();

            Microsoft.Office.Interop.Excel.Range range = Sheet.get_Range("A2", MaxColumn + "2");
            Sheet.ListObjects.Add(Microsoft.Office.Interop.Excel.XlListObjectSourceType.xlSrcRange, range, null,
                    Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes).Name = "Table1";

            for (int i = 0; i < Columns.Count; i++)
            {
                if (Columns[i] != null && Columns[i].ToString() != "")
                {
                    string Sql = "SELECT " + (GlobalVariables.SysLang ? "ArabicCaption" : "LatinCaption")+ " FROM " + GlobalVariables.ReferenceFileName + " WHERE TableName = '"+ frm.TableName + "' AND FieldName ='" + Columns[i] + "'";
                    Sheet.Cells[2, i + 1] = DataAccess.ExecuteScalar<string>(Sql);
                    Sheet.Cells[1, i + 1] = Columns[i].ToString();
                    Sheet.Rows[1].Hidden = true;
                }
            }

            ExcelApp.Visible = true;
        }
        catch (Exception ex)
        {
            xExceptions.ShowExceptionInfo(ex, "FormManager : CreateExcelTemplate()");
        }
    }
    public static void GetFormFields(Control.ControlCollection Controls, ref List<string> Columns)
    {
        try
        {
            var Ctrls = from ctrl in Controls.OfType<Control>() orderby ctrl.TabIndex select ctrl;
            foreach (Control control in Ctrls)
            {
                if (control is xLabel)
                {
                    xLabel lbl = control as xLabel;
                    if (lbl.FieldName != null && lbl.FieldName != "")
                        Columns.Add(lbl.FieldName);
                }
                if (control.Controls.Count > 0) GetFormFields(control.Controls, ref Columns);
            }
        }
        catch (Exception ex)
        {
            xExceptions.ShowExceptionInfo(ex, "FormManager : GetFormFields()");
        }
    }

I need to order them as table created actually i need is

public static void GetFormFields(Control.ControlCollection Controls, ref List<string> Columns)
    {
        try
        {
           get columns from table this what i need according to order on table 
        }
        catch (Exception ex)
        {
            xExceptions.ShowExceptionInfo(ex, "FormManager : GetFormFields()");
        }
    }

Dataset Designer: "Unable to find connection MyConn (MySettings)1 for object 'MySettings'"

$
0
0

Everything was working well yesterday, but today when attempting to open and preview one of the queries of a tableadapter in my application's most crucial dataset, generates this error:

"Operation failed."

"Unable to find connection 'MyConn (MySettings)1' for object 'MySettings'. The connection string could not be found in application settings, or the data provider associated with the connection string could not be loaded. .'

 

I've searched these forums, newsgroups, google and come across a few examples of where the dataset designer has inserted additional connection lines within the xsd. However, this doesn't appear to have happened here.

If I get the latest stable build in its entirety from SourceSafe, I still have the same problem!

If I get a very old build from SourceSafe, I still have the problem!

This proves that there is nothing wrong with the xsd. Or, each time it is used, the Dataset designer goes off and does its own thing with it.

I'm able to open and configure the Query and using the Query Builder, execute a test of the query - which does exactly what I would have expected from the "Preview Data" button.

If I run the solution, no immediate problems. But calling the update method on one of the affected tables (although I get the error on ALL my datasets) at runtime (the solution compiles ok and runs) I get various SQL errors related to concurrency. One of my datasets bombs out when I attempt to open it with the above error, and additionally displays a critical message: "The specified procedure could not be found. (Exception from HRESULT: 0x8007007F).

The solution is a VB.NET solution, and this is a data access layer .dll assembly. The connection string is stored in MySettings.

Incidentally, I have tried to log a support incident with Microsoft, but can't as the online tool doesn't recognise my product ID when I type it in or use the downloadable tool. Does this indicate a potential problem with my VS2005 installation?

Please help, I'm absolutely tearing my hair out! (And so is my client - the solution was opened to issue a hotfix!)

Also my VS2005 installation, after 5-6 hours continuous work uses up around 1.5gb of RAM. Connected problems?

Many thanks!

(p.s. BRING ON VS2005 SP1!!!)

Read any csv file to DataGridView in visual basic WindowsForm

$
0
0
Open .csv file using OpenFileDialog and access that on DataGridView.That's all.

Is there a dual row DataGridView ?

$
0
0

Hello all. Is it possible to make a DataGridView with two rows representing one DataRow ? In international trading, there is document called packing list. After typing, the printing of a packing showing two lines for each DataRow. For example :

item  qty  unit   number of boxes  net weight  gross weight

1     10   pcs          2                        2                3

       20   pcs                                    4                6

2.     5   pcs           4                         5               6

       20  pcs                                     20             24

On the screen when we type data, we want all input controls to resemble what we see in the printing, data of a box appearing on the first line and data of total boxes on the second line. I saw a program 12 years ago that can do that. It actually used two DataRows to represent one row of data we want (an illusion of course). Eight years ago I used Delphi to write the same program. Delphi provided something like a belt that I could put TextBox on it. I put two rows of TextBox on a belt. A belt acts like a row of a DataGridView. When three rows are loaded to a program, three belts are created. The whole thing  worked just like a DataGridVew.

Now that I am rewriting our old Delphi program using C#. I could not find anything like the delphi belt mentioned above. Does any one know how to achieve the above dual line DataGridView ?

Thank you all.

How to turn off "AutoGenerate" of columns when a DataGridView is data-bound

$
0
0

I have a Windows form that has a DataGridView on it.  I have bound the DataGridView to show data, that I specifed,  from the database (I defined the cells that I want to see through the property page).  But, the DataGridView is showing the cells I defined AND the data being returned from the dataset.

So, the question - what property do I set to turn off the default columns being returned from the dataset?  With a web app, there is an "AutoGenerate Columns" that you set to true or false.  What's the WinForm equivalent?

Thanks,

Dexter
 

DataGridView: Setting CurrentCell sets selected, does not move cursor.

$
0
0

The code:

        /// <summary>
        /// This happens AFTER the rows have been added, but BEFORE the CurrentRow has been changed.  Therefore you can't use the currentRow to
        /// find out where you are pointing.  The e.Rowindex is WRONG when you add rows programmatically.  Had to use ROWCOUNT instead.
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void purchase_Order_DetailDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (!isFetchingData)
            {
                DataGridView Grid = (sender as DataGridView);
                int lastrow = Grid.RowCount-1;

                if (lastrow > 0)
                {                    
                    DataGridViewCell Cell= Grid.Rows[lastrow].Cells["Pick"];                                        
                    Grid.CurrentCell = Grid.Rows[lastrow].Cells["Pick"];
                    Grid.BeginEdit(true);
                }
            }
        }

The Result:

CurrentCell in Row 1, Cursor in 0

It seems the correct cell is "Selected" but the cursor is in the previous row,

So, there are 2 rows, 0 and 1, and 1 should be "Current".  The debugger confirms.

Yet the "Cursor" is still in Row 0.

I have tried refreshing the grid at various places to null effect.

The desired behavior is to have the cursor in the new row in the "Pick" column after an add (Add row button pressed).


I'd rather live with false hope than with false despair.

How to prevent click event button on datagridview executed if i click outside button

$
0
0

Problem

I have datagridview have button if i focus on it and click outisde button meaning click in any place on datagridview header

it will execute the button code although i dont make click on button only I focus on it .

i work on visual studio 2015 windows form 

How to solve this problem please ?

actually i need when focus on button and click on button execute button click but in my case 

button click execute if i click outside button .


DataGridView DoubleClick Event stopped working

$
0
0

The DataGridView Double_Click event stopped firing. Double clicking on a row only causes the MouseClick event to fire. If I comment out the MouseClick event the DoubleClick event then fires.

I'm working in VB.net VS2010.  Both events had been functioning properly up until today. Any suggestions would be greatly appreciated.

Regards,

Doug

Find and remove Duplicate rows from DatagridView

$
0
0

Hi,

I have coded for find and remove the duplicate rows from datagrid view based on ID column(See the snap). But it not working...

Thanks to any one could assist me...

 private void DelDuplicateData()
        {
            List<string> list1 = new List<string>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string str = dataGridView1.Rows[i].Cells[2].Value.ToString();
                if (!list1.Contains(str))
                {
                    list1.Add(dataGridView1.Rows[i].Cells[2].Value.ToString());
                }
                else
                {
                    dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                }

            }
           
        }

DataGridView raising SetCurrentCellAddressCore Exception

$
0
0
I've built an Enter-Firendly DataGridView control, which basically just treats the enter key as the tab key, allowing the user to move quickly between cells just by pressing enter.  It's very useful for accounting applications.

Anyway, it works fine when the user just uses the enter key, or the arrow keys, to move between cells.  It breaks down however when the user uses the mouse.  I get the error: Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.

Here is my code.  Sorry one piece is in VB while the other is in C#.  I had packaged the DataGridView extension into a class library, and used c# which is my prefered language, but the consuming application was already written in VB.

First the control:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace EnterFriendlyDataGridView
{
    public class DataGridViewEnter : DataGridView
    {
        public string lastColumn;
        public event EventHandler rowEntryComplete;

        //This override causes the DataGridView to use the enter key in a similar way as
        //the tab key

        protected override bool ProcessDialogKey(Keys keyData)
        {
            Keys key = (keyData & Keys.KeyCode);

            if (key == Keys.Enter)
            {
                return this.ProcessEnterKeyAsTab(keyData);
            }
            return base.ProcessDialogKey(keyData);
        }

        public bool ProcessEnterKeyAsTab(Keys keyData)
        {

            if (base.Columns[base.CurrentCell.ColumnIndex].Name == lastColumn)
            {
                // raise an event which, when handled, ends edit on the current cell
                if (rowEntryComplete != null)
                    rowEntryComplete(this, null);

                return true;
            }
            else
            {
                // possibly only do this if balances don't match
                return base.ProcessTabKey(keyData);
            }
        }

        protected override bool ProcessDataGridViewKey(KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
                return this.ProcessEnterKeyAsTab(e.KeyData);
            else
                return base.ProcessDataGridViewKey(e);
        }

        public void manualHome()
        {
            base.ProcessHomeKey(Keys.Home);
        }

        public void manualTab()
        {
            base.ProcessTabKey(Keys.Tab);
        }
    }
}


And now the host application:

#Region "DataGridView methods"

    Private Sub dgvSerialNumbers_RowEntryComplete(ByVal sender As Object, ByVal e As EventArgs) Handles dgvSerialNumbers.rowEntryComplete
        'end edit mode, which fires the CellEndEdit event
        dgvSerialNumbers.BeginEdit(False)
        dgvSerialNumbers.EndEdit()

    End Sub

    Private Sub dgvSerialNumbers_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgvSerialNumbers.CellClick
        Dim a As Integer = 1
    End Sub

    Private Sub dgvSerialNumbers_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgvSerialNumbers.CellEndEdit

        Dim fromSN, toSN As String
        If e.ColumnIndex = 0 Then

            fromSN = dgvSerialNumbers.Rows(e.RowIndex).Cells(0).Value

            If dgvSerialNumbers.Rows(e.RowIndex).Cells(1).Value = "" Then
                'Copy the From SN to the ToSN
                dgvSerialNumbers.Rows(e.RowIndex).Cells(1).Value = fromSN
                dgvSerialNumbers.manualTab()
                dgvSerialNumbers.BeginEdit(True)
            End If

        Else

            If dgvSerialNumbers.Rows(e.RowIndex).Cells(1).Value Is Nothing Then Exit Sub

            'this is where we interpolate To SN's based on From SN's
            fromSN = dgvSerialNumbers.Rows(e.RowIndex).Cells(0).Value
            toSN = dgvSerialNumbers.Rows(e.RowIndex).Cells(1).Value

            If toSN.Length < fromSN.Length Then
                toSN = fromSN.Substring(0, fromSN.Length - toSN.Length) + toSN
                dgvSerialNumbers.Rows(e.RowIndex).Cells(1).Value = toSN
            End If

            dgvSerialNumbers.manualTab()

        End If
    End Sub

#End Region

Sum of the columns' FillWeight values cannot exceed 65535

$
0
0

HI All,

I know this question is been asked multiple times in this forum but I am still facing the problem.

I have looked at the following link.

http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/bd291e0c-dee8-45c1-bee1-54509fdf3c4f/

http://www.timvw.be/adding-datagridviewcolumns-lots-of-them/

But I am not able to find the solution to the problem. I am using VS2010 and I am trying to bind 900 columns.

The code looks like this:

 

DataGridViewColumn[] columns =newDataGridViewColumn[ds.Tables[0].Columns.Count];

dgTab.AutoGenerateColumns =

false;

 

for (int i = 0; i < columns.Length; ++i)

{

 

DataGridViewColumn column =newDataGridViewTextBoxColumn();

column.FillWeight = 1;

columns[i] = column;

}

 

this.dgTab.Columns.AddRange(columns);

dgTab.DataSource =

null;

dgTab.DataSource = ds.Tables[0];

 

=================================================================================================================

 If I set column.FillWeight = 0, I get run time error saying FillWeight cannot be 0. That why I have set it to 1.

Also, I have a row enter event where I  am trying to get the parentId

int participantID = Convert.ToInt32(dgTab.Rows[e.RowIndex].Cells["ParentID"].Value);

I get error saying:

Column named ParentID cannot be found.
Parameter name: columnName

I think the data is not getting binded to the grid properly. Please share the code which will resolve the problem.

 

Import excel with border design

$
0
0

I tried to import excel to datagridview before and I did it successfully, but it is possible to import the cells contain together with the border design?




Error getting SQLite to datagridview

$
0
0

Hi folks,

I getting an error when i try to get database members to datagridview. The error i get is unhandled exception 'source' more detail is not there.

The method i use:

public int LaadData(DataGridView dgv)
        {

            string SQL = "SELECT * FROM Persoon";
            using (var dt = new DataTable())
            {

                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    //cmd.Connection = con;
                    //cmd.CommandText = SQL;
                    SQLiteDataAdapter da = new SQLiteDataAdapter(SQL, con);
                    da.Fill(dt);
                }
                dgv.DataSource = dt; // error
            }

            
            con.Close();
            return dgv.Rows.Count;
        }

Hopefully another knows the correct answer.

Rinaldo


Greetings from Amsterdam the Netherlands

Getting System.ArgumentOutofRangeException when hitting ESC on new row on bound datagridview

$
0
0
Need some help troubleshooting this exception I keep getting.  I've bound a CollectionBase IBindingList class to the datagridview.  If I click on a new row, then click on the new row again to edit values, and then hit escape I get this error message.  Don't even know how I'd catch this exception.  Anyone got clues on this one?  Thanks.

System.ArgumentOutOfRangeException was unhandled
  Message="Specified argument was out of the range of valid values.\r\nParameter name: rowIndex"
  Source="System.Windows.Forms"
  ParamName="rowIndex"
  StackTrace:
       at System.Windows.Forms.DataGridView.GetCellDisplayRectangle(Int32 columnIndex, Int32 rowIndex, Boolean cutOverflow)
       at System.Windows.Forms.DataGridView.GetCellAdjustedDisplayRectangle(Int32 columnIndex, Int32 rowIndex, Boolean cutOverflow)
       at System.Windows.Forms.DataGridView.InvalidateCellPrivate(Int32 columnIndex, Int32 rowIndex)
       at System.Windows.Forms.DataGridView.OnCellCommonChange(Int32 columnIndex, Int32 rowIndex)
       at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.CancelCurrentEdit()
       at System.Windows.Forms.DataGridView.DataGridViewDataConnection.CancelRowEdit(Boolean restoreRow, Boolean addNewFinished)
       at System.Windows.Forms.DataGridView.CancelEditPrivate()
       at System.Windows.Forms.DataGridView.CancelEdit(Boolean endEdit)
       at System.Windows.Forms.DataGridView.ProcessEscapeKey(Keys keyData)
       at System.Windows.Forms.DataGridView.ProcessDataGridViewKey(KeyEventArgs e)
       at System.Windows.Forms.DataGridView.ProcessKeyPreview(Message& m)
       at System.Windows.Forms.Control.ProcessKeyPreview(Message& m)
       at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
       at System.Windows.Forms.Control.WmKeyChar(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
       at System.Windows.Forms.TextBox.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(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at SWBC.DesktopApps.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       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()


how to display html file in webbrowser control in datagridviewcell

$
0
0

Hi am adding webbrowser control in datagridviewcell with reference of Here My question is that how to add html file in that cell.

Thanks in advance...


Experience the innovation with perfection.

Get form to copy text form textbox to database

$
0
0

Hi all

I need help, I created a form with textboxes.

The values of the textboxes must be added to the database "DebtorData".

The form containing the textboxes is named "DebtorAdd"

Here is the code I have:

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

namespace SparesPOS
{
    public partial class DebtorAdd : Form
    {
        public DebtorAdd()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlConn = new SqlConnection("connectionString"))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add("@DebtorID", SqlDbType.Int).Value = DebIDtxt.Text;
                cmd.Parameters.Add("@DebtorName", SqlDbType.VarChar, 50).Value = DebNametxt.Text;
                cmd.Parameters.Add("@DebtorPhone1", SqlDbType.VarChar, 50).Value = DebPh1txt.Text;
                cmd.Parameters.Add("@DebtorPhone2", SqlDbType.VarChar, 50).Value = DebPh2txt.Text;
                cmd.Parameters.Add("@DebtorFax", SqlDbType.VarChar, 50).Value = DebFaxtxt.Text;
                cmd.Parameters.Add("@DebtorEmail", SqlDbType.VarChar, 50).Value = DebEmtxt.Text;
                cmd.Parameters.Add("@DebtorAddr1", SqlDbType.VarChar, 50).Value = DebAdr1txt.Text;
                cmd.Parameters.Add("@DebtorAddr2", SqlDbType.VarChar, 50).Value = DebAdr2txt.Text;
                cmd.Parameters.Add("@DebtorAddr3", SqlDbType.VarChar, 50).Value = DebAdr3txt.Text;
                cmd.Parameters.Add("@DebtorAddr4", SqlDbType.VarChar, 50).Value = DebAdr4txt.Text;
                cmd.Parameters.Add("@DebtorPostCode", SqlDbType.VarChar, 50).Value = debPosCtxt.Text;
                cmd.Parameters.Add("@DebtorContact1", SqlDbType.VarChar, 50).Value = DebCont1txt.Text;
                cmd.Parameters.Add("@DebtorContact2", SqlDbType.VarChar, 50).Value = DebCont2txt.Text;
                cmd.Parameters.Add("@DebtorLimit", SqlDbType.VarChar, 50).Value = DebLimittxt.Text;

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "DebtorAdd";
                cmd.Connection = sqlConn;
                cmd.Connection.Open();

                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch { }
            }
        }
    }
}

Refresh the ComboBox once created items in the same ComboBox

$
0
0

Dear all,

With refer the attached snap,  it did not refresh the ComboBox once i created the new Project or add new Mark. Even I tried ComboBox1.Refresh() it did not refresh without close and reopen the Dialog box (Form). 

Thanks to any one can assist me...


Clear Cell DatagridView in Cell Validating event

$
0
0

Hi,

I want to know how to delete a cell datagridview value in Cell validating event after or before setting e.cancel to true.

I tried the following:

1- Datgridview.Item(e.columnIndex, e.RowIndex).Value = System.Dbnull.Value

2- Datagridview.CurrentCell.value = system.dbnull.value

But they did not work. Can Anyone help me please,

Thank you

 

Failing to log in on button click

$
0
0

My form refuses to execute a login.

I have watched tutorials, googled, tried various codes, but still no success.

Here is my code:

        private void LoginFirst_Load(object sender, EventArgs e)
        {
        }
        private void Loginbtn_Click(object sender, EventArgs e)
        {
            string s1 = Usertxt.Text;
            string s2 = Passtxt.Text;

            string connect = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\simeo\source\repos\SparesPOS\SparesPOS\PartsPosDB.mdf";

            SqlConnection conn = new SqlConnection(connect);

            conn.Open();
            SqlCommand cmd = new SqlCommand("Log", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@User", s1);
            cmd.Parameters.AddWithValue("@Pass", s2);
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter spd = new SqlDataAdapter();
            spd.SelectCommand = cmd;
            spd.Fill(dt);
            conn.Close();

            if (dt.Rows.Count > 0)
            {
                this.Hide();
                MainForm f1 = new MainForm();
                f1.Visible = true;
                this.Visible = false;
            }
            else
            {
                MessageBox.Show("failed to log in");
            }
        }

Please Help

Viewing all 2535 articles
Browse latest View live


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