.NET 4.x Не создаётся элемент панели при нажатии кнопки
06.02.2024, 20:36. Показов 749. Ответов 9
Приветствую. У меня возникла проблемка. Пишу практику на тему "Форум". Так как у меня бд идентична с одногруппником, я брал у него части кода, когда мне были не понятны некоторые моменты. По факту, моё приложение представляет себя, как обычный Форум. Создать Тему, а там уже под темы и сообщения в этих темах. С созданием Форума всё прекрасно. Данные записываются в бд и код успешно его запрашивает, а вот уже с созданием под темы, тут проблема. Когда нажимаю на кнопку создать эту под тему, где мне надо ещё будет ввести название этой под темы и нажать на кнопку "Применить", данные в бд записываются, но вот сама панель, которая должна создаваться как кнопка, не создаётся. Либо не отображается. Не понятно. Не буду скидывать весь проект, скину нужные.
Forumi.cs (Интерфейс когда нажимаешь на созданный Форум, где есть элементы Создания/удаления обсуждений)
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
| using MySql.Data.MySqlClient;
using Mysqlx.Crud;
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;
namespace Forum
{
public partial class Forumi : Form
{
public int SelectedThemeID { get; set; }
public int SelectedTopicID { get; set; }
public string SelectedTopicName { get; set; }
public string SelectedCreationDate { get; set; }
public string UserName { get; set; }
public string UserLogin { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
public int UserId { get; set; }
public int SelectedForumID;
private string topicName;
private int topicID;
private string creationDate;
private Panel selectedPanel;
public class ForumData
{
public List<ForumInfo> Forums { get; set; } = new List<ForumInfo>();
public int SelectedForumID { get; set; }
}
public ForumData ForumDataInstance { get; set; } = new ForumData();
public class ForumInfo
{
public int UserId { get; set; }
public int ForumID { get; set; }
public int ThemeID { get; set; }
public string Description { get; set; }
}
public Forumi(int selectedTopicID, string selectedTopicName, int UserId)
{
InitializeComponent();
SelectedTopicID = selectedTopicID;
SelectedTopicName = selectedTopicName;
this.UserId = UserId;
SelectedForumID = 0;
}
private void Forumi_Load(object sender, EventArgs e)
{
na_obs.FlatStyle = FlatStyle.Flat;
na_obs.FlatAppearance.BorderSize = 1;
add_obs.FlatStyle = FlatStyle.Flat;
add_obs.FlatAppearance.BorderSize = 1;
del_obs.FlatStyle = FlatStyle.Flat;
del_obs.FlatAppearance.BorderSize = 1;
if (!string.IsNullOrEmpty(SelectedTopicName))
{
name_form.Text = SelectedTopicName;
}
string query = "SELECT `Forum_ID`, `Theme_ID`, `Описание` FROM `Форумы` WHERE `Theme_ID` = @themeID";
DataTable forumsTable = new DataTable();
DB db = new DB();
try
{
db.openConnection();
MySqlCommand command = new MySqlCommand(query, db.GetConnection());
command.Parameters.AddWithValue("@themeID", SelectedTopicID); // Предположим, что SelectedTopicID содержит выбранное Theme_ID
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(forumsTable);
foreach (DataRow row in forumsTable.Rows)
{
Panel nPanel = new Panel();
nPanel.Size = new Size(390, 71);
nPanel.BackColor = Color.White;
nPanel.Click += ForumPanel_Click;
nPanel.Tag = Convert.ToInt32(row["Forum_ID"]);
if (panel_obs.Controls.Count == 0)
{
nPanel.Location = new Point(3, 3);
}
else
{
Panel lastPanel = (Panel)panel_obs.Controls[panel_obs.Controls.Count - 1];
nPanel.Location = new Point(3, lastPanel.Bottom + 3);
}
panel_obs.Controls.Add(nPanel);
string forumDescription = row["Описание"].ToString();
Label label = new Label();
label.Text = forumDescription;
label.Font = new Font("MS Reference Sans Serif", 12);
label.AutoSize = true;
label.TextAlign = ContentAlignment.MiddleLeft;
nPanel.Controls.Add(label);
}
if (selectedPanel != null)
{
topicID = SelectedForumID;
topicName = ((Label)selectedPanel.Controls[0]).Text;
string dateQuery = "SELECT `Дата_создания` FROM `Форумы` WHERE `Forum_ID` = @forumID";
{
try
{
db.openConnection();
MySqlCommand dateCommand = new MySqlCommand(dateQuery, db.GetConnection());
dateCommand.Parameters.AddWithValue("@forumID", SelectedForumID);
object result = dateCommand.ExecuteScalar();
if (result != null)
{
creationDate = result.ToString();
}
else
{
// Обработка случая, если дата создания не найдена
creationDate = "Дата создания неизвестна";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Обработка ошибки получения даты создания
creationDate = "Ошибка получения даты создания";
}
finally
{
db.closeConnection();
}
}
}
}
catch (Exception ex)
{
// Обработка исключения, например, вывод в консоль или логирование
Console.WriteLine(ex.Message);
}
finally
{
// Всегда закрываем соединение с базой данных, даже в случае ошибки
db.closeConnection();
}
}
private void ForumPanel_Click(object sender, EventArgs e)
{
if (sender is Panel clickedPanel)
{
// Выделение выбранной панели
if (selectedPanel != null)
{
selectedPanel.BackColor = Color.White;
}
clickedPanel.BackColor = Color.LightBlue;
selectedPanel = clickedPanel;
}
}
private void DeleteForum(int forumID)
{
string deleteQuery = "DELETE FROM `Форумы` WHERE `Forum_ID` = @forumID";
DB db = new DB();
try
{
db.openConnection();
MySqlCommand deleteCommand = new MySqlCommand(deleteQuery, db.GetConnection());
deleteCommand.Parameters.AddWithValue("@forumID", forumID);
deleteCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
db.closeConnection();
}
}
private void na_main_Click(object sender, EventArgs e)
{
this.Hide();
Mainvhod mains = new Mainvhod();
mains.UserId = UserId;
mains.UserName = UserName;
mains.UserLogin = UserLogin;
mains.Password = Password;
mains.Mail = Mail;
mains.SelectedTopicID = topicID;
mains.SelectedTopicName = topicName;
mains.SelectedCreationDate = creationDate;
mains.Show();
}
private void LoadForums()
{
string query = "SELECT `Forum_ID`, `Theme_ID`, `Описание` FROM `Форумы` WHERE `Theme_ID` = @themeID";
DataTable forumsTable = new DataTable();
DB db = new DB();
try
{
db.openConnection();
MySqlCommand command = new MySqlCommand(query, db.GetConnection());
command.Parameters.AddWithValue("@themeID", SelectedTopicID);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(forumsTable);
panel_obs.Controls.Clear();
foreach (DataRow row in forumsTable.Rows)
{
{
Panel newPanel = new Panel();
newPanel.Size = new Size(414, 71);
newPanel.BackColor = Color.White;
newPanel.Click += ForumPanel_Click;
if (panel_obs.Controls.Count == 0)
{
newPanel.Location = new Point(3, 3);
}
else
{
Panel lastPanel = (Panel)panel_obs.Controls[panel_obs.Controls.Count - 1];
newPanel.Location = new Point(3, lastPanel.Bottom + 3);
}
panel_obs.Controls.Add(newPanel);
string forumDescription = row["Описание"].ToString();
Label label = new Label();
label.Text = forumDescription;
label.Font = new Font("MS Reference Sans Serif", 12);
label.AutoSize = true;
label.TextAlign = ContentAlignment.MiddleLeft;
newPanel.Controls.Add(label);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error loading forums: " + ex.Message);
}
finally
{
db.closeConnection();
}
}
private void na_obs_Click(object sender, EventArgs e)
{
if (selectedPanel != null)
{
string forumDescription = ((Label)selectedPanel.Controls[0]).Text;
this.Hide();
MessageTem tem = new MessageTem();
tem.UserId = UserId;
tem.UserName = UserName;
tem.Password = Password;
tem.Mail = Mail;
tem.SelectedForumID = Convert.ToInt32(selectedPanel.Tag); // Set the SelectedForumID
tem.SelectedTopicID = SelectedTopicID;
tem.SelectedTopicName = SelectedTopicName;
tem.SelectedCreationDate = SelectedCreationDate;
tem.SelectedForumID = Convert.ToInt32(selectedPanel.Tag);
tem.SelectedForumName = ((Label)selectedPanel.Controls[0]).Text;
tem.Show();
}
else
{
// Если ни один форум не выбран, выведите сообщение об ошибке или предупреждение
MessageBox.Show("Выберите форум перед открытием.");
}
}
private void add_obs_Click(object sender, EventArgs e)
{
nametemcs ntem = new nametemcs(this);
ntem.UserId = UserId;
ntem.UserName = UserName;
ntem.UserLogin = UserLogin;
ntem.Password = Password;
ntem.Mail = Mail;
ntem.SelectedThemeID = SelectedThemeID;
ntem.FormClosed += (s, args) => LoadForums();
ntem.Show();
}
private void del_obs_Click(object sender, EventArgs e)
{
if (selectedPanel != null)
{
int forumID = Convert.ToInt32(selectedPanel.Tag);
DeleteForum(forumID);
// Удалить панель из коллекции
panel_obs.Controls.Remove(selectedPanel);
selectedPanel = null; // Обнулить selectedPanel после удаления
}
else
{
MessageBox.Show("Выберите форум перед удалением.");
}
}
private void panel_obs_Paint(object sender, PaintEventArgs e)
{
}
}
} |
|
nametemcs.cs (При нажатии на кнопку "Создать новый форум" всплывает этот интерфейс, где надо ввести название темы и после нажатие на кнопку "Применить" должен создать панель в виде кнопки)
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
| using MySql.Data.MySqlClient;
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;
namespace Forum
{
public partial class nametemcs : Form
{
public int SelectedForumID { get; set; }
public int SelectedThemeID { get; set; }
public string UserName { get; set; }
public string UserLogin { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
public int UserId { get; set; }
private Forumi _form;
public nametemcs(Forumi form)
{
InitializeComponent();
_form = form;
}
private void CreateForum(string description, int themeID, string createdBy, DateTime creationDate)
{
DB db = new DB();
string query = "INSERT INTO `Форумы` (`Theme_ID`, `Описание`, `Создан пользователем`, `Дата создания`) VALUES (@themeID, @description, @createdBy, @creationDate)";
using (MySqlCommand command = new MySqlCommand(query, db.GetConnection()))
{
command.Parameters.AddWithValue("@themeID", themeID);
command.Parameters.AddWithValue("@description", description);
command.Parameters.AddWithValue("@createdBy", createdBy);
command.Parameters.AddWithValue("@creationDate", creationDate.ToString("dd.MM.yyyy"));
try
{
db.openConnection();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
db.closeConnection();
}
}
this.Close();
}
private void accept_Click(object sender, EventArgs e)
{
string forumDescription = NaTema.Text;
// Получаем текущую дату и время
DateTime currentDate = DateTime.Now;
// Получаем имя пользователя из свойства UserName
string createdBy = UserName;
CreateForum(forumDescription, SelectedThemeID, createdBy, currentDate);
}
}
} |
|
MessageTem.cs (Интерфейс где после нажатия на панель которая должна создавать, должен перекидывать в этот интерфейс)
| C# | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
| using MySql.Data.MySqlClient;
using System;
using System.Net.Mime;
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.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;
namespace Forum
{
public partial class MessageTem : Form
{
public string SelectedForumName { get; set; }
public int SelectedForumID { get; set; }
public int SelectedThemeID { get; set; }
public int SelectedTopicID { get; set; }
public string SelectedTopicName { get; set; }
public string SelectedCreationDate { get; set; }
public string UserName { get; set; }
public string UserLogin { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
public int UserId { get; set; }
private string topicName;
private int topicID;
private string creationDate;
public class MessageInfo
{
public int User_ID { get; set; }
public string UserName { get; set; }
public int Forum_ID { get; set; }
public int Topic_ID { get; set; }
public string Text { get; set; }
public string Date { get; set; }
}
private List<Panel> messagePanels = new List<Panel>();
public MessageTem()
{
InitializeComponent();
}
private void MessageTem_Load(object sender, EventArgs e)
{
sent.FlatStyle = FlatStyle.Flat;
sent.FlatAppearance.BorderSize = 0;
namain.FlatStyle = FlatStyle.Flat;
namain.FlatAppearance.BorderSize = 0;
if (!string.IsNullOrEmpty(SelectedForumName))
{
NameT.Text = SelectedForumName;
}
LoadMessages(SelectedForumID);
}
private void LoadMessages(int forumId)
{
string messagesQuery = "SELECT u.`UserName`, m.`Text`, m.`Date` FROM `Сообщения` m " +
"INNER JOIN `Пользователи` u ON m.`User_ID` = u.`User_ID` " +
"WHERE m.`Forum_ID` = @forumID AND m.`Forum_ID` IS NOT NULL AND m.`Forum_ID` <> 0";
DataTable messagesTable = new DataTable();
DB db = new DB();
try
{
db.openConnection();
MySqlCommand command = new MySqlCommand(messagesQuery, db.GetConnection());
command.Parameters.AddWithValue("@forumID", forumId);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(messagesTable);
// Clear existing message panels
foreach (var panel in messagePanels)
{
MessBox.Controls.Remove(panel);
}
messagePanels.Clear();
int initialYPosition = messagePanels.Count > 0
? messagePanels[messagePanels.Count - 1].Bottom + 3 // Use the last panel's bottom position
: 3;
int yOffset = 3; // Offset between messages
// Display messages
int rowCount = messagesTable.Rows.Count;
Console.WriteLine($"Number of rows retrieved: {rowCount}");
foreach (DataRow row in messagesTable.Rows)
{
// Create and configure the Panel and Label for each message
Panel newPanel = new Panel();
newPanel.Size = new Size(363, 69);
newPanel.BackColor = SystemColors.HighlightText;
Label messageLabel = new Label();
messageLabel.Text = $"User: {row["UserName"]}, Text: {row["Text"]}, Date: {row["Date"]}";
messageLabel.AutoSize = true;
// Position the Label within the Panel
messageLabel.Location = new Point(5, 5);
newPanel.Controls.Add(messageLabel);
// Add the new Panel to the MassPanel
MessBox.Controls.Add(newPanel);
messagePanels.Add(newPanel);
}
if (rowCount == 0)
{
Console.WriteLine("No messages found for the selected forum.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
db.closeConnection();
}
}
private void namain_Click(object sender, EventArgs e)
{
this.Hide();
Mainvhod mains = new Mainvhod();
mains.UserId = UserId;
mains.UserName = UserName;
mains.UserLogin = UserLogin;
mains.Password = Password;
mains.Mail = Mail;
mains.SelectedTopicID = topicID;
mains.SelectedTopicName = topicName;
mains.SelectedCreationDate = creationDate;
mains.Show();
}
private void sent_Click(object sender, EventArgs e)
{
DB db = new DB();
string messageText = textM.Text;
// Проверка на пустой текст
if (string.IsNullOrWhiteSpace(messageText))
{
MessageBox.Show("Введите текст сообщения.");
return;
}
try
{
db.openConnection();
// Запрос для вставки сообщения в текущий форум
string insertMessageQuery = "INSERT INTO `Сообщения` (`User_ID`, `Forum_ID`, `Текст сообщения`, `Дата размещения`) " +
"VALUES (@UserId, @ForumId, @MessageText, NOW())";
try
{
MySqlCommand command = new MySqlCommand(insertMessageQuery, db.GetConnection());
command.Parameters.AddWithValue("@UserId", UserId);
command.Parameters.AddWithValue("@ForumId", SelectedForumID);
command.Parameters.AddWithValue("@MessageText", messageText);
command.ExecuteNonQuery();
Panel newPanel = new Panel();
newPanel.Size = new Size(363, 49);
newPanel.Location = new Point(3, MessBox.Controls.Count * (newPanel.Height + 3));
newPanel.BackColor = SystemColors.HighlightText;
Label messageLabel = new Label();
messageLabel.Text = messageText;
messageLabel.AutoSize = true;
messageLabel.Location = new Point(5, 5);
newPanel.Controls.Add(messageLabel);
MessBox.Controls.Add(newPanel);
messagePanels.Add(newPanel);
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при отправке сообщения: " + ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при открытии соединения: " + ex.Message);
}
finally
{
textM.Text = string.Empty;
db.closeConnection();
}
}
}
} |
|
Вот всё что в принципе связанно с этой частью. Если вам кажется, что всё такое себе, не судите, я только начинающий в С# и толком в этом языке не шарю.
0
|