Как сделать окно авторизации c visual studio
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.13.42356
using System.Data;namespace Link_DB
static string host = «localhost»;
static string database = «dbtest»;
static string userDB = «ecco»;
static string password = «password»;
public static string strProvider = «server=» + host + «;Database=» + database + «;User ;Password font-size: 14px; color: #1a0e95; display: table-row-group;» dir=»ltr»> public bool Open()
strProvider = «server=» + host + «;Database=» + database + «;User ;Password font-size: 14px; color: #1a0e95; display: table-row-group;» dir=»ltr»> conn = new MySqlLink(strProvider);
Create Login and Register System with C# Winforms
Many developers in recent years have been using C# to develop their applications. In this tutorial, we’ll go through a simple example of how to create a basic user authentication in C#.
Introduction
C# or C-sharp is an object-oriented programming language developed by Microsoft. C# or C-sharp runs on a framework called the .Net framework.
The language has created many applications like:
- Web applications
- Mobile applications
- Computer games
- Desktop applications
- Database applications
- Virtual reality applications
Prerequisites
To follow this article along it would be helpful to have the following:
- An editor, in my case, I’ll be using Visual Studio.
- Some basic C# and SQL knowledge.
- Knowledge on how to run relational database management in this case, we will use MySQL.
- Visual Studio knowledge and how to create projects.
Step I: Create a database and table with required columns
Create table command:
Step II: Create a project
Create a Visual Studio project by clicking on File -> New -> Project and then select Visual C#. From the window, choose Windows Forms App(.Net Framework). Give your application a name. Then click ok. The project will come with default form called Form 1.
Step III: Create a config class to execute MySQL queries
Since C# is object-oriented, we will create a class that will handle the execution of queries that we will use in our program.
From the Solution Explorer window right-click and select add -> New Item -> Class. Name the class Config.cs the click on the button add.
- Add MySQL.Data Library by right-clicking on solution explorer window, then Manage Nuget packages, then search for MySQL.Data Library and install.
- Add the following class to help in the execution of MySQL queries.
- Now that we have Config.cs, we can execute any MySQL statement.
Step IV: Create register windows form
In Microsoft Visual Studio, create a new project. Choose project -> Add Windows Form from File submenu in the left corner, give the form a name Register , and click Add.
We have two Windows form classes that is Form1.cs and Register.cs.
Step V: Design login and register interface
Login form
- Click on Form1.cs in Solution Explorer, and on the form that displays, add three buttons, two textboxes, and two labels.
The first button will be the register button, that launch the Register form. The second button will be the Login button. When the second button is clicked, it will query the database with the input entered. The second button will execute the login MySQL query. The third button will close the application.
The first textbox will allow the username input for login, while the second textbox will enable the password’s input. These two inputs will be passed to the SQL.
The labels will indicate the functionality of the two textboxes.
Register form
- Click on Register.cs in the Solution Explorer and on the form that displays add two buttons, three textboxes, and three labels.
The first button will be a register button to save data entered, and the second one will be an exit button that will close the Register form.
The first textbox will allow the input of the names for the user. The second textbox will allow input of the user’s username. The third textbox is for entering the password.
The labels will or show the functionality of the three textboxes.
Step VI: Login logic
- Initialize the Config file in Form1.cs to allow us to access the database with ease.
On click of the register button, add the following code.
On click of the login button, add the following code.
On click of the exit button, add the following code.
Step VII: Register logic
- Initialize the Config file in Register.cs to allow us to access the database with ease.
On click of the exit button, add the following code.
On click of the register button, add the following code to save the information.
Find the above application in GitHub Login and Register application.
Conclusion
From the example above, we have seen how we can use C# to create a Desktop system with a login functionality. The object-oriented functionality helps in code re-use without doing much coding from scratch.
Как сделать авторизацию в C: руководство и примеры рабочего кода
С вопросом: «Как сделать авторизацию в С?» рано или поздно сталкивается любой разработчик приложения на этом языке. Для чего нужна авторизация? По разным причинам. Основная из них — это предоставление более полной услуги или информации авторизованным пользователям.
То есть если пользователь пришел как «гость», то ему, возможно, доступна информация лишь для ознакомления с проектом ; если же пользователь авторизовался, то он может воспользоваться полным функционалом. Такая модель взаимоотношени й с пользователями используется очень часто.
Как сделать авторизацию в С
Способов сделать авторизацию множество. Мы сегодня рассмотрим более-менее «стандартную» ситуацию, когда разрабатывается Виндовс-приложение на С в Visual Studio и нужно сделать авторизацию с сохранением логинов и паролей в MySQL.
Для удобства мы разбили весь процесс на несколько шагов.
Создаем базу данных
-
«id»(INT), добавив атрибут «AUTO_INCREMENT»;
-
«name»(VARCHAR(100));
-
«title»(VARCHAR(100));
-
«address»(VARCHAR(100)).
Создаем проект
-
открыть меню по пути «Файл-Новый-Проект»;
-
по этому пути вам откроется окошко с новым проектом, где нужно будет заполнить пункты «Name», «Location», «Solution name».
Создаем интерфейс формы
-
«login»;
-
«password».
Настраиваем соединение с базой данных
Чтобы настроить соединение с базой данных , нужно будет создать специальный класс, например , «link». Вот как это можно реализовать:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;namespace Link_DB
<
class link
<
MySql.Data.MySqlClient.MySqlLink conn;
string myLinkString;
static string host = «localhost»;
static string database = «dbtest»;
static string userDB = «ecco»;
static string password = «password»;
public static string strProvider = «server=» + host + «;Database=» + database + «;User ;Password font-size: 14px; color: #1a0e95; display: table-row-group;» dir=»ltr»> public bool Open()
<
try
<
strProvider = «server=» + host + «;Database=» + database + «;User ;Password font-size: 14px; color: #1a0e95; display: table-row-group;» dir=»ltr»> conn = new MySqlLink(strProvider);
conn.Open();
return true;
>
catch (Exception er)
<
MessageBox.Show(«Соединение нарушено! » + er.Message, «Информация»);
>
return false;
> public void Close()
<
conn.Close();
conn.Dispose();
> public DataSet ExecuteDataSet(string sql)
<
try
<
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, «result»);
return ds;
>
catch (Exception ex)
<
MessageBox.Show(ex.Message);
>
return null;
> public MySqlDataReader ExecuteReader(string sql)
<
try
<
MySqlDataReader reader;
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
return reader;
>
catch (Exception ex)
<
MessageBox.Show(ex.Message);
>
return null;
> public int ExecuteNonQuery(string sql)
<
try
<
int affected;
MySqlTransaction mytransaction = conn.BeginTransaction();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
affected = cmd.ExecuteNonQuery();
mytransaction.Commit();
return affected;
>
catch (Exception ex)
<
MessageBox.Show(ex.Message);
>
return -1;
>
>
>
Реализуем код авторизации
Возвращаемся к созданной форме и добавляем следующий код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;namespace Link_DB
<
public partial class AForm1 : AForm
<
link con = new link();
string id, username, password, firstname, lastname, address;
public AForm1()
<
InitializeComponent();
> private void btnLogin_Click(object sender, EventArgs e)
<
try
< if (txtUsername.Text != "" && txtPassword.Text != "")
<
con.Open();
string query = «select id,username,password,firstname,lastname,address from user WHERE username ='» + txtUsername.Text + «‘ AND password ='» + txtPassword.Text + «‘»;
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
<
while (row.Read())
<
id = row[«id»].ToString();
username = row[«username»].ToString();
password = row[«password»].ToString();
firstname = row[«firstname»].ToString();
lastname = row[«lastname»].ToString();
address = row[«address»].ToString();
> MessageBox.Show(«Data found your name is » + firstname + » » + lastname + » » + » and your address at » + address);
>
else
<
MessageBox.Show(«Данные не найдены», «Информация»);
>
>
else
<
MessageBox.Show(«Login или Password заполнены верно», «Информация»);
>
>
catch
<
MessageBox.Show(«Соединение прервано», «Информация»);
>
>
>
>
Заключение
Теперь вы знаете, как можно сделать авторизацию в С. Помните, что это всего лишь один подход из десятков.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
#2 — Создание дизайна для окна авторизации
При разработке дизайна всегда стоит подготавливать макет готовой программы. Такой макет можно создать в PhotoShop , Figma, Sketch или в любых других программах, которые отвечают за разработку дизайна. Имея готовый макет вам будет проще расставлять объекты, добавлять к ним цвета, устанавливать форму и производить другие манипуляции.
На основе WinForms можно создавать абсолютно любой дизайн программы. Пример программы:
Библиотеки
Помимо использования стандартных стилей, вы всегда можете воспользоваться сторонними библиотеками, которые позволят быстрее создавать еще более красивые дизайны для приложений.
Несколько таких библиотек приведено ниже:
- Специализированная библиотека Bunify ;
- Фреймворк WPF ;
- Xamarin Forms .
Создание дизайна
В основе своей, создание дизайна разбивается на несколько этапов:
- Добавление объектов на главное окно;
- Добавление стилей для объектов. Можно добавить стили не только стандартные, но и стили из различных библиотек;
- Добавление обработчиков событий.
Звучит просто, хотя на деле все сложнее. Вам стоит самостоятельно попрактиковаться и создать несколько вариантов дизайна программы.