столкнулся с проблемой. Допустим, существует форма InsertTransactions в которой присутствуют текстовые поля и кнопки. А также существует форма DataBaseClients в которой существует лист с данными подключенная к б.д. и кнопка btnEdit_Click. При выборе нужной строки в листе б.д. данные должны заноситься в текстовые поля формы InsertTransactions. Но при этом открывается еще одна форма InsertTransactions. Как сделать так, чтобы данные заносились в уже открытую форму InsertTransactions, а не создавала новую. Код формы InsertTransactions:
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.Data.SqlClient;
using System.Runtime.InteropServices;
namespace RealEstateAgency.Forms_of_action
{
public partial class InsertTransactions : Form
{
private SqlConnection sqlConnection = null;
private int id;
public InsertTransactions(SqlConnection connection, int id)
{
InitializeComponent();
sqlConnection = connection;
this.id = id;
this.ControlBox = false;
this.MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea;
textBox1.Enabled = false;
}
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hWnd, int wMsg, int wParam, int lParam);
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
private void btnDelete_Click(object sender, EventArgs e)
{
Close();
}
private void button4_Click(object sender, EventArgs e)
{
Data_Base.DataBaseClients dataBaseClient = new Data_Base.DataBaseClients();
dataBaseClient.Show();
}
private async void InsertTransactions_Load(object sender, EventArgs e)
{
SqlCommand getClientsInfoCommand = new SqlCommand("SELECT [Surname], [Name], [MiddleName], [Budget], [Area], [Rooms], [Floor], [Sqaure], [Email] FROM [Clients] WHERE [Id]=@Id", sqlConnection);
getClientsInfoCommand.Parameters.AddWithValue("Id", id);
SqlDataReader sqlReader = null;
try
{
sqlReader = await getClientsInfoCommand.ExecuteReaderAsync();
while (await sqlReader.ReadAsync())
{
textBox4.Text = Convert.ToString(sqlReader["Surname"]) + " " + Convert.ToString(sqlReader["Name"]) + " " + Convert.ToString(sqlReader["MiddleName"]);
textBox5.Text = Convert.ToString(sqlReader["Budget"]);
textBox6.Text = Convert.ToString(sqlReader["Area"]);
textBox7.Text = Convert.ToString(sqlReader["Rooms"]);
textBox8.Text = Convert.ToString(sqlReader["Floor"]);
textBox9.Text = Convert.ToString(sqlReader["Sqaure"]);
textBox10.Text = Convert.ToString(sqlReader["Email"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlReader != null && !sqlReader.IsClosed)
sqlReader.Close();
}
}
}
}
Код формы DataBaseClients:
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.Data.SqlClient;
using System.Runtime.InteropServices;
namespace RealEstateAgency.Data_Base
{
public partial class DataBaseClients : Form
{
private SqlConnection sqlConnection;
private List<string[]> rows = new List<string[]>();
private List<string[]> filteretedList = null;
public DataBaseClients()
{
InitializeComponent();
this.ControlBox = false;
this.MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea;
}
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hWnd, int wMsg, int wParam, int lParam);
private async void DataBaseClients_Load(object sender, EventArgs e)
{
try
{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\RealEstateAgency\RealEstateAgency\Database.mdf;Integrated Security=True";
sqlConnection = new SqlConnection(connectionString);
await sqlConnection.OpenAsync();
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.View = View.Details;
listView1.Columns.Add("Номер");
listView1.Columns[listView1.Columns.Count - 1].Width = 100;
listView1.Columns.Add("Фамилия");
listView1.Columns[listView1.Columns.Count - 1].Width = 170;
listView1.Columns.Add("Имя");
listView1.Columns[listView1.Columns.Count - 1].Width = 125;
listView1.Columns.Add("Отчество");
listView1.Columns[listView1.Columns.Count - 1].Width = 150;
listView1.Columns.Add("Бюджет");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
listView1.Columns.Add("Район");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
listView1.Columns.Add("Кол-во комнат");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
listView1.Columns.Add("Этаж");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
listView1.Columns.Add("Площадь");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
listView1.Columns.Add("E-mail");
listView1.Columns[listView1.Columns.Count - 1].Width = 250;
await LoadClientsAsync();
}
catch (Exception)
{
MessageBox.Show("Не удалось установить соединение с базой данный!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DataBaseClients_FormClosing(object sender, FormClosingEventArgs e)
{
if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed)
sqlConnection.Close();
}
private async Task LoadClientsAsync()
{
SqlDataReader sqlReader = null;
string[] row = null;
SqlCommand getClientsCommand = new SqlCommand("SELECT * FROM [Clients]", sqlConnection);
try
{
sqlReader = await getClientsCommand.ExecuteReaderAsync();
while (await sqlReader.ReadAsync())
{
row = new string[]
{
Convert.ToString(sqlReader["Id"]),
Convert.ToString(sqlReader["Surname"]),
Convert.ToString(sqlReader["Name"]),
Convert.ToString(sqlReader["MiddleName"]),
Convert.ToString(sqlReader["Budget"]),
Convert.ToString(sqlReader["Area"]),
Convert.ToString(sqlReader["Rooms"]),
Convert.ToString(sqlReader["Floor"]),
Convert.ToString(sqlReader["Sqaure"]),
Convert.ToString(sqlReader["Email"])
};
rows.Add(row);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlReader != null && !sqlReader.IsClosed)
{
sqlReader.Close();
}
}
RefreshList(rows);
}
private void RefreshList(List<string[]> list)
{
listView1.Items.Clear();
foreach (string[] s in list)
{
listView1.Items.Add(new ListViewItem(s));
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
Forms_of_action.InsertTransactions update = new Forms_of_action.InsertTransactions(sqlConnection, Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text));
update.Show();
}
else
{
MessageBox.Show("Ни одна строка не была выделена!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}