Home c# Data output from database in DataGridView

Data output from database in DataGridView

Author

Date

Category

could not find a topic with the answer to my question.
There is a database on the local MYSQL server.
Create Windows Forms application, the connection is set to the database, but the data is not displayed in DataGridView. More precisely, they are displayed, but writes System.Collections.Genic.List`1 [System.String] for the place of data and then only in the 1st column. I can not understand what it is. Please tell me how to make a workable program

Here is the connection code from the database. The Public List [] SELECT () method creates a list for output.

class dbconnect
  {
    Private MySqlConnection Connection;
    Private String Server, Database, UID, Password;
    Public dbconnect ()
    {
      Initialize ();
    }
    Private Void Initialize ()
    {
      Server = "LocalHost";
      Database = "Catalog_Personal";
      UID = "ROOT";
      password = "";
      String ConnectionString;
      ConnectionString = "Server =" + Server + ";" + "Database =" +
      Database + ";" + "UID =" + UID + ";" + "Password =" + password + ";";
      Connection = New MySqlConnection (ConnectionString);
    }
    // Open the connection
    Private Bool OpenConnection ()
    {
      Try.
      {
        Connection.open ();
        RETURN TRUE;
      }
      Catch (Mysqxception EX)
      {
        // When processing errors, you can base the answer of your application.
        // by error number.
        // Two most common error numbers when connected:
        // 0: Unable to connect to the server.
        // 1045: Invalid username and / or password.
        Switch (ex .number)
        {
          Case 0:
            MessageBox.Show ("Unable to connect to the server," +
              "Contact the admin panel");
            Break;
          Case 1045:
            MessageBox.Show ("Invalid username / password," +
              "Please try again");
            Break;
        }
        RETURN FALSE;
      }
    }
    // Close the connection
    Private Bool CloseConnection ()
    {
      Try.
      {
        Connection.Close ();
        RETURN TRUE;
      }
      Catch (Mysqxception EX)
      {
        MessageBox.Show (EX.Message);
        RETURN FALSE;
      }
    }
    Public List & LT; String & GT; [] SELECT ()
    {
      String Query = "SELECT * from Personal";
      // Create a list to save output
      List & lt; String & GT; [] List = New List & LT; String & GT; [4];
      List [0] = New List & LT; String & GT; ();
      List [1] = New List & LT; String & GT; ();
      List [2] = New List & LT; String & GT; ();
      List [3] = New List & LT; String & GT; ();
      // Open the connection
      if (this.openconnection () == TRUE)
      {
        // Create a team
        MySqlCommand CMD = New MySqlcommand (Query, Connection);
        // Create a data reader and perform the read command
        Mysqldatareader datareader = cmd.executerader ();
        While (DataReader.Read ())
        {
          List [0] .add (DataReader [0] .tostring ());
          List [1] .add (DataReader [1] .tostring ());
          List [2] .add (DataReader [2] .tostring ());
          List [3] .add (DataReader [3] .tostring ());
        }
        this.CloseConnection ();
        RETURN LIST;
      }
      ELSE.
      {
        RETURN LIST;
      }
    }
  }

code in Form1

Public Partial Class Form1: Form
  {
    Public Form1 ()
    {
      Initializecomponent ();
      Loaddata ();
    } 
Private Void Loaddata ()
    {
      Dbconnect db = new dbconnect ();
      Foreach (Var S in db.select ())
      {
        DataGridView1.Rews.add (s);
      }
    }
  }

That’s what happens as a result, I attach a screen


Answer 1, Authority 100%

Consider more of your example.
Here you are “sketched” on the form of control, and you need to start programming work with them. What would I like …

First, do not rush to create a database immediately and connect to it. For quick prototyping, the database application is not needed and even harmful, because distracts time and attention to working with it.

Secondly, in ad. It is necessary to highlight the layers, minimally 3: layer of display (visual interface), layer of the object model with a cat. Your arrival works. and storage layer (this is just working with the database).

Let’s start with the creation of the model. Our model is quite simple. I added more static. Method for cloning class instance, why? Explain below.

Public Class Employee
{
  Public int ID {Get; SET; }
  // Sequence number for display in DGV
  Public int ordernumber {get; SET; }
  //name
  Public String FirstName {Get; SET; }
  //surname
  Public String LastName {Get; SET; }
  Public String Phone {Get; SET; }
  Public Employee (int ID, String FirstName = "& lt;? & gt;", String LastName = "& lt;? & gt;", String Phone = "& lt;? & gt;")
  {
    Id = id;
    FirstName = firstName;
    LastName = LastName;
    Phone = Phone;
  }
  /// & LT; Summary & GT;
  /// Obtaining a cloned instance
  /// & LT; / Summary & GT;
  /// & lt; param name = "Employee" & gt; Existing instance & lt; / param & gt;
  /// & lt; Returns & gt; Clone of an existing employee & lt; / returns & gt;
  Public Static Employee Getclone (Employee Employee)
  {
    if (Employee is null)
      Throw New System.argumentNullexception (Nameof (Employee));
    Return New Employee (Employee.ID)
    {
      FirstName = Employee.firstName
      LastName = Employee.lastName,
      Phone = Employee.Phone,
    };
  }
  Public Override String Tostring ()
  {
    RETURN $ "{ID}: {firstName} {LastName}";
  }
}

Storage layer Let’s start with abstraction, with the creation of the repository interface.

Public Interface Imployeerepository
{
  // Obtaining all
  Task & Lt; Result & lt; List & lt; Employee & gt; & gt; & gt; Betemployees ();
  // Addition
  Task & Lt; Result & lt; int & gt; & gt; AddEmployee (Employee Employee);
  // Removal
  Task & Lt; Result & lt; int & gt; & gt; Removeemployee (int id);
  //update
  Task & Lt; Result & lt; int & gt; & gt; UpdateEmployee (Employee EMP);
}

Here we declare all methods we need for work. By the way, you can start directly from an empty interface, and as you need to add the necessary members to it. Note that it is supposed to work in asynchronous mode, and yes, there is still some RESULT & LT; T & GT; !

Result & lt; T & GT; is the example of the so-called. Monads, specials. A class to return a result If an error or the result may occur in the method, it may be equal to NULL . More SeeVideo . Here is its code

/// & lt; summary & gt;
/// Monad Result to return the result instead of NULL
/// and for cases when exception occurs, and the result from the method
/// you need to return some kind
/// & LT; / Summary & GT;
/// & lt; TypeParam name = "T" & gt; & lt; / typeparam & gt;
Public Class Result & Lt; T & GT;
{
  Public Readonly T Value;
  Public Readonly String Error;
  // Ctors.
  Public Result (T Value)
  {
    Value = Value;
    Error = string.empty;
  }
  Public Result (String Error)
  {
    Error = error;
  } 
Public Bool Hasvalue = & GT; String.ISNULOREMPTY (Error);
  Public Static Implicit Operator Bool (Result & Lt; T & GT; Result)
  {
    Return result.hasvalue;
  }
}

Now return to the application interface. Shape code such

Public Partial Class Mainform: Form
{
  // Data source for DGV
  Private Bindingsource _Bsemployees;
  // Editable employee
  Private bindingsource _bscurretemployee;
  // Work with database
  Private ImployeEerepository _repo;
  Public Mainform ()
  {
    Initializecomponent ();
    StartPosition = FormstartPosition.centerscreen;
    Text = "Example of working with MySQL";
    // Installing binding
    Setbindings ();
    this.Load + = MainForm_load;
  }
  Private Void Mainform_Load (Object Sender, Eventargs E)
  {
    // Test repository
    _repo = new testrepository ();
    // Data loading
    Loaddata ();
    // Buttons
    _buttonadd.click + = buttonadd_click;
    _Buttonremove.Click + = Buttonremove_Click;
    _Buttonsave.Click + = Buttonsave_Click;
    _Buttonnext.Click + = Buttonnext_Click;
    _ButtonPrev.Click + = ButtonPrev_Click;
    // Click on the line in DGV
    _datagridviewemployees.mouseclick + = (s, a) = & gt; SetCurrenPloyee ();
  }
  Private Void Setbindings ()
  {
    _Bsemployees = new bindingsource ();
    _Bsemployees.DataSource = Typeof (List & LT; Employee & gt;);
    // Bindings for DGV
    _datagridviewemployees.autogenerateColumns = false;
    _datagridviewemployees.datasource = _Bsemployees;
    // Binding in columns
    _Columnnumber.DataPropertyName = Nameof (Employee.Ordernumber);
    _ColumnFirstName.DatapropertyName = Nameof (Employee.firstName);
    _columnlastname.datapropertyName = Nameof (Employee.lastName);
    _Columnphone.DatapropertyName = NameOF (Employee.Phone);
    // Textball
    _bscurrentEmployee = new bindingsource ();
    _bscurrentEmployee.datasource = New List & LT; Employee & gt; {new employee (0)};
    _TextBoxFirstName.Databindings.Add ("Text", _bscurrenPloyeee, Nameof (Employee.firstName));
    _textboxlastname.databindings.add ("text", _bscurrenployeee, nameof (employee.lastname));
    _TextBoxphone.databindings.add ("text", _bscurrenployeee, nameof (employee.phone));
  }
  Private Async Void Loaddata ()
  {
    // Receive
    Var Result = await _repo.getemployees ();
    IF (Result)
    {
      // Remove
      List & lt; Employee & gt; Employees = result.Value;
      // Prime former
      int i = 1;
      Employees.Foreach (E = & GT; E.OrderNumber = I ++);
      // Display
      _Bsemployees.datasource = Employees;
      _Bsemployees.movefirst ();
      SetCurrenPloyee ();
    }
    ELSE.
    {
      MessageBox.Show (Result.error, "Error", MessageBoxButtons.ok, MessageBoxicon.error);
    }
  }
  Private Void Buttonadd_Click (Object Sender, Eventargs E)
  {
    // Cursor on the last
    _Bsemployees.movelast ();
    // Solder
    INT Number = (_Bsemployees.current AS Employee) .Ordernumber + 1;
    // Add new
    _Bsemployees.add (New Employee (0) {OrderNumber = Number});
    // Select it
    _Bsemployees.movenext ();
    SetCurrenPloyee ();
    // Select the name for editing
    _TextBoxFirstName.Focus ();
  }
  Private Async Void Buttonsave_Click (Object Sender, Eventargs E)
  {
    Switchonwaiting ();
    VAR Current = (Employee) _bscurrenployeee.current;
    Result & lt; int & gt; result;
    Try.
    {
      if (current.id == 0)
      {
        // add a new employee
        Result = await _repo.addemployee (Current);
      }
      ELSE.
      {
        // otherwise update the existing employee
        result = await _repo.updateEmployee (Current);
      }
      IF (Result)
      {
        // Re-read the data 
Loaddata ();
      }
    }
    Finally
    {
      Switchoffwaiting ();
    }
    If (! Result)
    {
      MessageBox.Show (Result.error, "Error", MessageBoxButtons.ok, MessageBoxicon.error);
    }
  }
  Private Async Void Buttonremove_Click (Object Sender, Eventargs E)
  {
    Switchonwaiting ();
    // Get current
    VAR Employee = (Employee) _Bsemployees.current;
    Result & lt; int & gt; result;
    Try.
    {
      // Remove from the database
      result = await _repo.removeemployee (employee.id);
      IF (Result)
      {
        // Delete from display
        _Bsemployees.Remove (Employee);
        _Bsemployees.movefirst ();
        SetCurrenPloyee ();
      }
    }
    Finally
    {
      Switchoffwaiting ();
    }
    If (! Result)
    {
      MessageBox.Show (Result.error, "Error", MessageBoxButtons.ok, MessageBoxicon.error);
    }
  }
  Private Void ButtonPrev_Click (Object Sender, Eventargs E)
  {
    _Bsemployees.movePrevious ();
    SetCurrenPloyee ();
  }
  Private Void Buttonnext_Click (Object Sender, Eventargs E)
  {
    _Bsemployees.movenext ();
    SetCurrenPloyee ();
  }
  Private Void SetCurrenPloyee ()
  {
    if (_Bsemployees.count & gt; 0)
    {
      _bscurrentEmployee.list [0] = Employee.Getclone ((Employee) _Bsemployees.current);
    }
    ELSE.
    {
      _bscurrentEmployee.list [0] = New Employee (0);
    }
    _bscurretemployee.resetitem (0);
  }
  Private void SwitchonWaiting ()
  {
    Foreach (Var Button in this.controls.oftype & lt; Button & gt; ())
    {
      button.Enabled = false;
    }
    _datagridviewemployees.enabled = false;
    Cursor = cursors.waitcursor;
  }
  Private void SwitchFFWAITING ()
  {
    Foreach (Var Button in this.controls.oftype & lt; Button & gt; ())
    {
      Button.Enabled = True;
    }
    _DataGridViewEmployees.EnableD = True;
    CURSOR = CURSORS.DEFAULT;
  }
}

What I would like to pay attention.

We work through bindings, we use two instances of bindingsource , one for DataGridView , the second for textbox of the current editable or created new employee. By clicking on DGV or switching to Pomes. The clone is created to the next or previous one and is attached to textboxam. Made so in order to eliminate the simultaneous change in the properties of the selected employee in DGV and the user understood that you need to press the button to save to memorize the changes.

In the MainForm_load () method, a connection to the fake database _repo = new testrepository (); or rather the class implementing ImployeEerepository with test data. Consider it

class testrepository: iremployeerepository
{
  Private List & lt; Employee & gt; _employees;
  Public TestRepository ()
  {
    _Employees = new list & lt; Employee & gt;
    {
      NEW EMPLOYEE (1, "Ivan", "Golunov", "+7561234567"),
      NEW EMPLOYEE (2, "Sergey", "Smirnov", "+77861234567"),
      NEW EMPLOYEE (3, "Daria", "Smirnova", "+798475563"),
      New Employee (4, "Cristina", "Semyazhko", "+7304985023"),
      NEW EMPLOYEE (5, "Vladimir", "Dragunov", "+73431234567"),
    };
  }
  Public Task & Lt; Result & lt; List & lt; Employee & gt; & gt; & gt; Betemployees ()
  {
    VAR Result = New List & LT; Employee & gt; ();
    Foreach (VAR E IN _Employees)
    {
      var Emp = New Employee (E.ID, E.FirstName, E.LastName, E.Phone);
      result.add (EMP);
    }
    Return Task.FromResult (New Result & Lt; List & lt; Employee & gt; & gt; (result));
  }
  Public Task & Lt; Result & LT; int & gt; & gt; AddEmployee (Employee Employee)
  {
    if (Employee is null)
      Throw New ArgumentNullexception (Nameof (Employee)); 
if (string.isnullorwhiteSpace (Employee.firstName)
      || String.ISNULLOREMPTY (Employee.firstName))
    {
      Return Task.FromResult (New Result & Lt; Int & GT; ("Enter the employee name."));
    }
    if (string.isnullorwhiteSpace (Employee.lastName)
      || String.ISNULLOREMPTY (Employee.lastName))
    {
      Return Task.FromResult (New Result & Lt; Int & GT; ("Enter the Family of the employee."));
    }
    if (Employee is null || employee.id & gt; 0)
      Throw New ArgumentNullexception (Nameof (Employee));
    if (_employees.count & gt; 0)
    {
      Employee.ID = _Employees.max (E = & gt; e.id) + 1;
    }
    ELSE.
    {
      Employee.id = 1;
    }
    _Employees.add (Employee);
    Return Task.FromResult (New Result & LT; int & gt; (1));
  }
  Public Task & Lt; Result & LT; int & gt; & gt; Removeemployee (int id)
  {
    if (id & lt; = 0)
      Throw New ArgumentException (Nameof (ID));
    var emp = _employees.firstordefault (E = & gt; e.id == id);
    if (EMP! = NULL)
    {
      _employees.remove (EMP);
    }
    Return Task.FromResult (New Result & LT; int & gt; (1));
  }
  Public Task & Lt; Result & LT; int & gt; & gt; UpdateEmployee (Employee Employee)
  {
    if (Employee is null)
      Throw New ArgumentNullexception (Nameof (Employee));
    if (string.isnullorwhiteSpace (Employee.firstName)
      || String.ISNULLOREMPTY (Employee.firstName))
    {
      Return Task.FromResult (New Result & Lt; Int & GT; ("Enter the employee name."));
    }
    if (string.isnullorwhiteSpace (Employee.lastName)
      || String.ISNULLOREMPTY (Employee.lastName))
    {
      Return Task.FromResult (New Result & Lt; Int & GT; ("Enter the Family of the employee."));
    }
    var emp = _employees.firstordefault (E = & gt; e.id == employee.id);
    if (EMP! = NULL)
    {
      Emp.FirstName = Employee.firstName;
      emp.lastname = employee.lastname;
      Emp.Phone = Employee.Phone;
    }
    Return Task.FromResult (New Result & LT; int & gt; (1));
  }
}

Imagine for a minute, you freelancer and your order for a similar program. You need to quickly develop a prototype and provide to the customer, so that he could run this prototype and see, evaluate, and so on. If you used to immediately connect to the real database, you would have any difficulties, it’s not true … And so without problems, compile and send an exhesive by mail.

Customer satisfied? 🙂 We write work with a real database.

class mysqlrepository: iremployeerepository
{
  Public MySqlRepository ()
  {}
  Private MysqlConnection GetConnection ()
  {
    var cs = configurationmanager.connectionstrings ["mysqlconn"]. Tostring ();
    Var Builder = New MySqlConnectionStringBuilder (CS);
    // To avoid problems with the Russian language
    Builder.characterset = "UTF8";
    Return New MySqlConnection (Builder.ConnectionString);
  }
  Public Async Task & Lt; Result & LT; List & lt; Employee & gt; & gt; & gt; Betemployees ()
  {
    var List = New List & lt; Employee & gt; ();
    Try.
    {
      Using (var con = getConnection ())
      Using (var cmd = con .CreateCommand ())
      {
        cmd.commandText = "SELECT * from Employees";
        con .Open ();
        Using (Var Reader = await cmd.executereaderasync ())
        {
          While (await Reader.Readasync ())
          {
            var EMP = New Employee (reader.getint32 (0));
            Emp.FirstName = Reader.getString (1);
            Emp.LastName = Reader.getString (2);
            Emp.Phone = Reader.getString (3);
            List.add (EMP);
          }
        }
      }
    }
    Catch (Mysqxception EX)
    { 
Return New Result & LT; List & LT; Employee & GT; & GT; (GetUserfriendlyerrorMessage (EX));
    }
    Catch (Exception Ex)
    {
      Return New Result & LT; List & lt; Employee & gt; & gt; (ex .Message);
    }
    Return New Result & LT; List & LT; Employee & GT; & GT; (List);
  }
  Public Async Task & Lt; Result & LT; int & gt; & gt; AddEmployee (Employee Employee)
  {
    if (Employee is null)
      Throw New ArgumentNullexception (Nameof (Employee));
    if (string.isnullorwhiteSpace (Employee.firstName)
      || String.ISNULLOREMPTY (Employee.firstName))
    {
      RETURN NEW RESULT & LT; INT & GT; ("Enter the employee name.");
    }
    if (string.isnullorwhiteSpace (Employee.lastName)
      || String.ISNULLOREMPTY (Employee.lastName))
    {
      RETURN NEW RESULT & LT; INT & GT; ("Enter the name of the employee.");
    }
    INT RESULT = 0;
    Try.
    {
      Using (var con = getConnection ())
      Using (var cmd = con .CreateCommand ())
      {
        cmd.commandText = "INSERT INTO EMPLOYES (FIRST_NAME, LAST_NAME, PHONE)" +
          "Values ​​(@FirstName, @LastName, @phone)";
        cmd.parameters.add (new mysqlparameter (@ firstname, mysqldbtype.varchar, 200)
        {Value = Employee.firstName});
        cmd.parameters.add (new mysqlparameter ("@ LastName", mysqldbtype.varchar, 300)
        {Value = employee.lastname});
        cmd.parameters.add (new mysqlparameter ("@ phone", mysqldbtype.varchar, 45)
        {
          Value = Employee.Phone ?? (Object) System.dbnull.Value
        });
        con .Open ();
        Result = await cmd.executenonqueryasync ();
      }
    }
    Catch (Mysqxception EX)
    {
      RETURN NEW RESULT & LT; INT & GT; (GetUserfriendlyerrormessage (EX));
    }
    Catch (Exception Ex)
    {
      RETURN NEW RESULT & LT; INT & GT; (EX.Message);
    }
    Return New Result & LT; Int & GT; (Result);
  }
  Public Async Task & Lt; Result & LT; int & gt; & gt; Removeemployee (int id)
  {
    if (id & lt; = 0)
      Throw New ArgumentException (Nameof (ID));
    INT RESULT = 0;
    Try.
    {
      Using (var con = getConnection ())
      Using (var cmd = con .CreateCommand ())
      {
        cmd.commandText = "Delete from Employees Where id = @ id";
        cmd.parameters.add (new mysqlparameter ("@ id", mysqldbtype.int32)
        {Value = id});
        con .Open ();
        Result = await cmd.executenonqueryasync ();
      }
    }
    Catch (Mysqxception EX)
    {
      RETURN NEW RESULT & LT; INT & GT; (GetUserfriendlyerrormessage (EX));
    }
    Catch (Exception Ex)
    {
      RETURN NEW RESULT & LT; INT & GT; (EX.Message);
    }
    Return New Result & LT; Int & GT; (Result);
  }
  Public Async Task & Lt; Result & LT; int & gt; & gt; UpdateEmployee (Employee Employee)
  {
    if (Employee is null)
      Throw New ArgumentNullexception (Nameof (Employee));
    if (string.isnullorwhiteSpace (Employee.firstName)
      || String.ISNULLOREMPTY (Employee.firstName))
    {
      RETURN NEW RESULT & LT; INT & GT; ("Enter the employee name.");
    }
    if (string.isnullorwhiteSpace (Employee.lastName)
      || String.ISNULLOREMPTY (Employee.lastName))
    {
      RETURN NEW RESULT & LT; INT & GT; ("Enter the name of the employee.");
    }
    INT RESULT = 0;
    Try.
    {
      Using (var con = getConnection ())
      Using (var cmd = con .CreateCommand ())
      {
        cmd.commandText = "Update Employees" +
          "Set first_name = @firstname, last_name = @lastname, phone = @phone" +
          "WHERE ID = @ ID";
        cmd.parameters.add (new mysqlparameter (@ firstname, mysqldbtype.varchar, 200)
        {Value = Employee.firstName});
        cmd.parameters.add (new mysqlparameter ("@ LastName", mysqldbtype.varchar, 300)
        {Value = employee.lastname}); 
cmd.Parameters.Add (new MySqlParameter ( "@ phone", MySqlDbType.VarChar, 45)
        {
          Value = employee.Phone ?? (Object) System.DBNull.Value
        });
        cmd.Parameters.Add (new MySqlParameter ( "@ id", MySqlDbType.Int32)
        {Value = employee.Id});
        con .Open ();
        result = await cmd.ExecuteNonQueryAsync ();
      }
    }
    Catch (Mysqxception EX)
    {
      return new Result & lt; int & gt; (GetUserFriendlyErrorMessage (ex));
    }
    Catch (Exception Ex)
    {
      return new Result & lt; int & gt; (ex.Message);
    }
    return new Result & lt; int & gt; (result);
  }
  private string GetUserFriendlyErrorMessage (MySqlException ex)
  {
    var message = String.Empty;
    Switch (ex .number)
    {
      Case 0:
        if (ex.InnerException.Message.Contains ( "Unknown"))
        {
          message = "Incorrect procedure or table.";
        }
        else if (ex.InnerException.Message.Contains ( "Access"))
        {
          message = "Invalid name or password.";
        }
        ELSE.
        {
          message = ex.Message;
        }
        Break;
      case 1042:
        message = "server at the specified address is not available." +.
          "\ NError expectations.";
        Break;
      Case 1045:
        message = "Invalid username or password" +
          "\ NPlease try again.";
        Break;
      Default:
        message = ex.Message;
        Break;
    }
    Return Message;
  }
}

In the method GetConnection () connection settings are read from the file App.config

& lt;? Xml version = "1.0" encoding = "utf-8" & gt?;
  & lt; Configuration & gt;
    & Lt; startup & gt;
      & Lt; supportedRuntime version = "v4.0" sku = / & gt "NETFramework, Version = v4.7.2.";
    & Lt; / startup & gt;
    & Lt; connectionStrings & gt;
      & Lt; add name = "MySqlConn"
      providerName = "MySql.Data.MySqlClient"
   connectionString = "Server = 192.168.0.250; Port = 3306; Database = EmployeesDb; Uid = admin;
   Pwd = Mysql17; "/ & gt;
   & Lt; / connectionStrings & gt;
 & lt; / configuration & gt;

To use this class, you need to return to the form of the code in the method MainForm_Load () to change the line to obtain a copy of the repository _repo = new MySqlRepository ();

Yes, and do not forget to first get the money from the customer:)

An example is here.


Answer 2, Authority 150%

In order to construct the connection string, you can use a special class builder.

When the connection is established, you have left only two cases in the switch / case, and the rest are discarded. As a result, the user does not receive any messages if something goes wrong. It is necessary, for example, to add an additional branch default.

Modern involves the use of these models. Class properties model must comply with columns in a database table. I do not know what your column, but judging by the form of the Name, Last Name, Telephone. Therefore, the class model will be such:

class Person
{
  public string FirstName {get; set; }
  public string LastName {get; set; }
  public string Phone {get; set; }
}

Add the required properties with the right types (for example, type int Id and so on. N.)

When reading data from the database, create an instance of our class model, fill in its properties, and add to the list.

class dbconnect
{
  private readonly MySqlConnection connection;
  Public dbconnect ()
  {
    var builder = new MySqlConnectionStringBuilder (); 
Builder.Server = "LocalHost";
    Builder.Database = "Catalog_Personal";
    Builder.userid = "root";
    //Builder.password = "";
    Connection = New MySqlConnection (Builder.ConnectionString);
  }
  Private Bool OpenConnection ()
  {
    Try.
    {
      Connection.open ();
      RETURN TRUE;
    }
    Catch (Mysqxception EX)
    {
      Switch (ex .number)
      {
        Case 0:
          MessageBox.Show ("Unable to connect to the server," +
            "Contact the admin panel");
          Break;
        Case 1045:
          MessageBox.Show ("Invalid username / password," +
            "Please try again");
          Break;
        Default:
          MessageBox.Show (EX.Message);
          Break;
      }
      RETURN FALSE;
    }
  }
  Private Void CloseConnection ()
  {
    Try.
    {
      Connection.Close ();
    }
    Catch (Mysqxception EX)
    {
      MessageBox.Show (EX.Message);
    }
  }
  Public List & LT; Person & GT; SELECT ()
  {
    String Query = "SELECT * from Personal";
    Var List = New List & LT; Person & GT; ();
    if (OpenConnection ())
    {
      Using (VAR CMD = New MySqlcommand (Query, Connection))
      Using (var datareader = cmd.executerader ())
      {
        While (DataReader.Read ())
        {
          Var Person = New Person ();
          Person.FirstName = DataReader.getString (0);
          Person.LastName = DataReader.getString (1);
          Person.Phone = DataReader.getString (2);
          List.Add (Person);
        }
      }
      Closeconnection ();
    }
    RETURN LIST;
  }
}

also use data binding (binding) instead of manual addition.

private void loaddata ()
{
  var db = new dbconnect ();
  DataGridView1.Datasource = db.select ();
}

Answer 3, Authority 50%

rewrote your code through mysqldataadapter, it has declined very much.

as an exercise, you can rewrite it through the models (it will be a little more and more complicated, but more correctly and flexible).

class dbconnect
  {
    Private MySqlConnection Connection;
    Private String Server, Database, UID, Password;
    Public dbconnect ()
    {
      Initialize ();
    }
    Private Void Initialize ()
    {
      ...
    }
    // Open the connection
    Private Bool OpenConnection ()
    {
      ...
    }
    // Close the connection
    Private Bool CloseConnection ()
    {
      ...
    }
    Public DataTable SELECT ()
    {
      var dt = new datatable ();
      if (this.openconnection () == TRUE)
      {
        Mysqldataadapter da = new mysqldataadapter ();
        Da.SelectCommand.Connection = this.connection;
        da.selectcommand.commandtext = "SELECT * FROM PERSONAL";
        DA.Fill (DT);
        this.CloseConnection ();
      }
      Return DT;
    }
  }

code in Form1

Public Partial Class Form1: Form
  {
    Public Form1 ()
    {
      Initializecomponent ();
      Loaddata ();
    }
    Private Void Loaddata ()
    {
      Dbconnect db = new dbconnect ();
      DataGridView1.Datasource = db.select ();
    }
  }

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions