Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Bu kodla, MenuStrip pencerenin üst kısmına taşı ve DataGridView bu menünün altına…

  1. User

    Bu kodla, MenuStrip pencerenin üst kısmına taşı ve DataGridView bu menünün altına yerleştir. Kontroller arasındaki mesafeler standart Windows Form arayüzünde olduğu gibi ayarlandı. Kodun fonksiyonelliği ve çalışan içeriğini hiç bir şekilde değiştirme. Sadece yapman gerekeni yap -> using System; using System.Windows.Forms; using Firebase.Database; using Firebase.Database.Query; using FirebaseAdmin; using Google.Apis.Auth.OAuth2; using System.Threading.Tasks; using System.Linq; using System.Drawing; using System.Collections.Generic; using System.IO; using System.Text;

    namespace Flashcard { public partial class MainForm : Form { // Firebase client private FirebaseClient firebaseClient;

        // UI Controls
        private DataGridView dataGridView;
        private TextBox txtTitle, txtCategory, txtContent, txtBackgroundColor, txtSearch;
        private CheckBox chkFavorite, chkPinned;
        private CheckBox chkFilterFavorites, chkFilterPinned; // Filtering CheckBoxes
        private Button btnAdd, btnUpdate, btnDelete, btnSearch, btnClear;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel statusLabel;
    
        // **Yeni Eklenen Kontroller**
        private MenuStrip menuStrip; // Menü Çubuğu
        private ToolStripMenuItem fileMenuItem, themeMenuItem; // Menü Öğeleri
        private ToolStripMenuItem saveAsMenuItem, lightModeMenuItem, darkModeMenuItem; // Alt Menü Öğeleri
    
        // ContextMenuStrip for column visibility
        private ContextMenuStrip columnContextMenu;
    
        // Sorting state
        private string currentSortColumn = "";
        private bool sortAscending = true;
    
        // Data storage
        private List<FlashcardItem> allFlashcards = new List<FlashcardItem>();
    
        // Current search term
        private string currentSearchTerm = "";
    
        // Dictionary to store column visibility state
        private Dictionary<string, bool> columnVisibilityState = new Dictionary<string, bool>();
    
        public MainForm()
        {
            InitializeComponent();
            InitializeFirebase();
            InitializeUI();
        }
    
        /// <summary>
        /// Initializes Firebase connection using the provided JSON credentials.
        /// </summary>
        private void InitializeFirebase()
        {
            var path = "flashcard-e7f47-firebase-adminsdk-om656-e70a5506c2.json";
            var credential = GoogleCredential.FromFile(path);
    
            // Check if FirebaseApp is already created to prevent duplicate initialization
            if (FirebaseApp.DefaultInstance == null)
            {
                FirebaseApp.Create(new AppOptions
                {
                    Credential = credential
                });
            }
    
            firebaseClient = new FirebaseClient("https://flashcard-e7f47-default-rtdb.europe-west1.firebasedatabase.app/");
        }
    
        /// <summary>
        /// Sets up the user interface components.
        /// </summary>
        private void InitializeUI()
        {
            this.Size = new Size(1000, 800);
            this.Text = "Flashcard Application";
    
            // **MenuStrip Oluşturma**
            menuStrip = new MenuStrip
            {
                Dock = DockStyle.Top // MenuStrip'i üstte konumlandır
            };
    
            // **File Menu**
            fileMenuItem = new ToolStripMenuItem("File");
            saveAsMenuItem = new ToolStripMenuItem("Save As");
            saveAsMenuItem.Click += SaveAsMenuItem_Click; // Event Handler
            fileMenuItem.DropDownItems.Add(saveAsMenuItem);
    
            // **Theme Menu**
            themeMenuItem = new ToolStripMenuItem("Theme");
            lightModeMenuItem = new ToolStripMenuItem("Light Mode");
            darkModeMenuItem = new ToolStripMenuItem("Dark Mode");
            lightModeMenuItem.Click += LightModeMenuItem_Click; // Event Handler
            darkModeMenuItem.Click += DarkModeMenuItem_Click; // Event Handler
            themeMenuItem.DropDownItems.Add(lightModeMenuItem);
            themeMenuItem.DropDownItems.Add(darkModeMenuItem);
    
            // **MenuStrip'e Menüleri Ekleme**
            menuStrip.Items.Add(fileMenuItem);
            menuStrip.Items.Add(themeMenuItem);
    
            // **Form'a MenuStrip'i Ekleme**
            this.MainMenuStrip = menuStrip;
            Controls.Add(menuStrip); // MenuStrip'i ilk olarak ekliyoruz
    
            // Initialize DataGridView
            dataGridView = new DataGridView
            {
                Dock = DockStyle.Top,
                Height = 400,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = false,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = true,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize,
                Top = menuStrip.Bottom // DataGridView'i MenuStrip'in altına yerleştiriyoruz
            };
            dataGridView.SelectionChanged += DataGridView_SelectionChanged;
            dataGridView.CellContentClick += DataGridView_CellContentClick;
            dataGridView.CellFormatting += DataGridView_CellFormatting;
            dataGridView.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick; // For sorting
            Controls.Add(dataGridView);
    
            // Konum ve boyutlar için sabit değerler
            int labelLeft = 10;
            int textBoxLeft = 150;
            int startTop = dataGridView.Bottom + 10; // DataGridView'in hemen altından başla
            int textBoxWidth = 300;
            int textBoxHeight = 25;
            int verticalSpacing = 35; // Kontroller arası boşluk
    
            int currentTop = startTop;
    
            // Etiketleri ve Metin Kutularını Oluştur
    
            // Category
            CreateLabel("Category:", labelLeft, currentTop);
            txtCategory = CreateTextBox("Category", textBoxLeft, currentTop, textBoxWidth);
            currentTop += verticalSpacing;
    
            // Title
            CreateLabel("Title:", labelLeft, currentTop);
            txtTitle = CreateTextBox("Title", textBoxLeft, currentTop, textBoxWidth);
            currentTop += verticalSpacing;
    
            // Content
            CreateLabel("Content:", labelLeft, currentTop);
            txtContent = CreateTextBox("Content", textBoxLeft, currentTop, textBoxWidth);
            currentTop += verticalSpacing;
    
            // Background Color
            CreateLabel("Background Color:", labelLeft, currentTop);
            txtBackgroundColor = CreateTextBox("Background Color", textBoxLeft, currentTop, textBoxWidth);
            currentTop += verticalSpacing;
    
            // İşlevsel CheckBox'lar
            chkFavorite = new CheckBox { Text = "Favorite", Top = currentTop, Left = textBoxLeft, Width = 80 };
            Controls.Add(chkFavorite);
    
            chkPinned = new CheckBox { Text = "Pinned", Top = currentTop, Left = textBoxLeft + 90, Width = 80 };
            Controls.Add(chkPinned);
    
            currentTop += verticalSpacing;
    
            // Butonları Yatay Olarak Hizala
            int buttonTop = currentTop + 10; // Biraz boşluk ekle
            int buttonLeft = labelLeft;
    
            btnAdd = CreateButton("Add", buttonLeft, buttonTop, 100);
            buttonLeft += 110;
    
            btnUpdate = CreateButton("Update", buttonLeft, buttonTop, 100);
            buttonLeft += 110;
    
            btnDelete = CreateButton("Delete", buttonLeft, buttonTop, 100);
    
            // Arama Metin Kutusu ve Butonları
            txtSearch = CreateTextBox("Search...", 580, dataGridView.Bottom + 10, 200);
            btnSearch = CreateButton("Search", 580, txtSearch.Bottom + 5, 100);
            btnClear = CreateButton("Clear", 690, txtSearch.Bottom + 5, 90);
    
            // Filtreleme CheckBox'ları
            chkFilterFavorites = new CheckBox
            {
                Text = "Show Favorites",
                Top = btnSearch.Bottom + 10,
                Left = 580,
                Width = 120
            };
            chkFilterFavorites.CheckedChanged += FilterCheckBoxChanged;
            Controls.Add(chkFilterFavorites);
    
            chkFilterPinned = new CheckBox
            {
                Text = "Show Pinned",
                Top = btnSearch.Bottom + 10,
                Left = 710,
                Width = 120
            };
            chkFilterPinned.CheckedChanged += FilterCheckBoxChanged;
            Controls.Add(chkFilterPinned);
    
            // StatusStrip
            statusStrip = new StatusStrip();
            statusLabel = new ToolStripStatusLabel();
            statusStrip.Items.Add(statusLabel);
            Controls.Add(statusStrip);
    
            // ContextMenuStrip for column visibility
            columnContextMenu = new ContextMenuStrip();
            // Note: We'll populate the ContextMenuStrip after loading data to ensure column information is available
    
            // Assign the MouseUp event to show the ContextMenuStrip on right-click
            dataGridView.MouseUp += DataGridView_MouseUp;
    
            // Event Handler for Form Load
            this.Load += MainForm_Load;
        }
    
        // Yeni bir CreateLabel metodu ekliyoruz
        private Label CreateLabel(string text, int left, int top)
        {
            Label label = new Label
            {
                Text = text,
                Left = left,
                Top = top,
                AutoSize = true
            };
            Controls.Add(label);
            return label;
        }
    
        /// <summary>
        /// Handles the Form Load event to initially load data and start real-time listener.
        /// </summary>
        private async void MainForm_Load(object sender, EventArgs e)
        {
            await LoadDataAsync();
            // RealTimeListener(); // Optional: Uncomment if you want real-time updates
        }
    
        /// <summary>
        /// Creates a TextBox with placeholder text and associated event handlers.
        /// </summary>
        private TextBox CreateTextBox(string placeholder, int left, int top, int width)
        {
            TextBox textBox = new TextBox
            {
                Left = left,
                Top = top,
                Width = width,
                Text = placeholder,
                ForeColor = Color.Gray
            };
            textBox.GotFocus += (sender, e) =>
            {
                if (textBox.Text == placeholder)
                {
                    textBox.Text = "";
                    textBox.ForeColor = Color.Black;
                }
            };
            textBox.LostFocus += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = placeholder;
                    textBox.ForeColor = Color.Gray;
                }
            };
            Controls.Add(textBox);
            return textBox;
        }
    
        /// <summary>
        /// Creates a Button with specified properties and assigns click event.
        /// </summary>
        private Button CreateButton(string text, int left, int top, int width)
        {
            Button button = new Button
            {
                Text = text,
                Left = left,
                Top = top,
                Width = width
            };
            button.Click += (sender, e) => ButtonClick(text);
            Controls.Add(button);
            return button;
        }
    
        /// <summary>
        /// Handles button click events by identifying the button text.
        /// </summary>
        private void ButtonClick(string buttonText)
        {
            switch (buttonText)
            {
                case "Add":
                    AddData();
                    break;
                case "Update":
                    UpdateData();
                    break;
                case "Delete":
                    DeleteData();
                    break;
                case "Search":
                    SearchData();
                    break;
                case "Clear":
                    ClearSearch();
                    break;
            }
        }
    
        /// <summary>
        /// Handles the "Save As" menu item click to save data in selected format.
        /// </summary>
        private void SaveAsMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "CSV files (*.csv)|*.csv|TSV files (*.tsv)|*.tsv|Text files (*.txt)|*.txt",
                Title = "Save As"
            };
    
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string extension = Path.GetExtension(saveFileDialog.FileName).ToLower();
                    // DataGridView'den verileri al
                    var data = (List<FlashcardItem>)dataGridView.DataSource;
    
                    // Verileri seçilen formata göre kaydet
                    switch (extension)
                    {
                        case ".csv":
                            SaveDataAsCsv(data, saveFileDialog.FileName, ',');
                            break;
                        case ".tsv":
                            SaveDataAsCsv(data, saveFileDialog.FileName, '\t');
                            break;
                        case ".txt":
                            SaveDataAsTxt(data, saveFileDialog.FileName);
                            break;
                        default:
                            MessageBox.Show("Unsupported file format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                    }
    
                    MessageBox.Show("Data saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error saving data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    
        /// <summary>
        /// Saves data as CSV or TSV file.
        /// </summary>
        private void SaveDataAsCsv(List<FlashcardItem> data, string filePath, char delimiter)
        {
            StringBuilder sb = new StringBuilder();
    
            // Başlık satırı
            sb.AppendLine(string.Join(delimiter.ToString(), "Category", "Title", "Content", "Favorite", "Pinned", "Timestamp", "BackgroundColor"));
    
            foreach (var item in data)
            {
                string[] fields = new string[]
                {
                    EscapeCsvField(item.category),
                    EscapeCsvField(item.title),
                    EscapeCsvField(item.content),
                    item.favorite.ToString(),
                    item.pinned.ToString(),
                    item.timestamp.ToString(),
                    EscapeCsvField(item.backgroundColor)
                };
    
                sb.AppendLine(string.Join(delimiter.ToString(), fields));
            }
    
            File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
        }
    
        /// <summary>
        /// Escapes CSV fields containing delimiter or quotes.
        /// </summary>
        private string EscapeCsvField(string field)
        {
            if (field.Contains(",") || field.Contains("\"") || field.Contains("\r") || field.Contains("\n"))
            {
                return $"\"{field.Replace("\"", "\"\"")}\"";
            }
            else
            {
                return field;
            }
        }
    
        /// <summary>
        /// Saves data as TXT file.
        /// </summary>
        private void SaveDataAsTxt(List<FlashcardItem> data, string filePath)
        {
            StringBuilder sb = new StringBuilder();
    
            foreach (var item in data)
            {
                sb.AppendLine($"Category: {item.category}");
                sb.AppendLine($"Title: {item.title}");
                sb.AppendLine($"Content: {item.content}");
                sb.AppendLine($"Favorite: {item.favorite}");
                sb.AppendLine($"Pinned: {item.pinned}");
                sb.AppendLine($"Timestamp: {item.timestamp}");
                sb.AppendLine($"BackgroundColor: {item.backgroundColor}");
                sb.AppendLine(new string('-', 50));
            }
    
            File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
        }
    
        /// <summary>
        /// Handles the Light Mode menu item click.
        /// </summary>
        private void LightModeMenuItem_Click(object sender, EventArgs e)
        {
            SetTheme(Color.White, Color.Black);
        }
    
        /// <summary>
        /// Handles the Dark Mode menu item click.
        /// </summary>
        private void DarkModeMenuItem_Click(object sender, EventArgs e)
        {
            SetTheme(Color.FromArgb(45, 45, 48), Color.White);
        }
    
        /// <summary>
        /// Sets the application's theme colors.
        /// </summary>
        private void SetTheme(Color backColor, Color foreColor)
        {
            this.BackColor = backColor;
            this.ForeColor = foreColor;
    
            foreach (Control control in this.Controls)
            {
                SetControlTheme(control, backColor, foreColor);
            }
    
            // DataGridView renklerini ayarla
            dataGridView.BackgroundColor = backColor;
            dataGridView.DefaultCellStyle.BackColor = backColor;
            dataGridView.DefaultCellStyle.ForeColor = foreColor;
            dataGridView.ColumnHeadersDefaultCellStyle.BackColor = backColor;
            dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = foreColor;
            dataGridView.RowHeadersDefaultCellStyle.BackColor = backColor;
            dataGridView.RowHeadersDefaultCellStyle.ForeColor = foreColor;
            dataGridView.GridColor = foreColor;
        }
    
        /// <summary>
        /// Recursively sets theme colors for controls.
        /// </summary>
        private void SetControlTheme(Control control, Color backColor, Color foreColor)
        {
            control.BackColor = backColor;
            control.ForeColor = foreColor;
    
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    SetControlTheme(child, backColor, foreColor);
                }
            }
        }
    
        /// <summary>
        /// Handles CellContentClick events for CheckBox columns to toggle favorite and pinned statuses.
        /// </summary>
        private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && (dataGridView.Columns[e.ColumnIndex].Name == "favorite" || dataGridView.Columns[e.ColumnIndex].Name == "pinned"))
            {
                var flashcard = (FlashcardItem)dataGridView.Rows[e.RowIndex].DataBoundItem;
                bool newValue = !(bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    
                if (dataGridView.Columns[e.ColumnIndex].Name == "favorite")
                {
                    flashcard.favorite = newValue;
                }
                else
                {
                    flashcard.pinned = newValue;
                }
    
                _ = UpdateFlashcardInDatabase(flashcard);
            }
        }
    
        /// <summary>
        /// Updates a flashcard in the Firebase database.
        /// </summary>
        private async Task UpdateFlashcardInDatabase(FlashcardItem flashcard)
        {
            try
            {
                await firebaseClient
                    .Child("flashcards")
                    .Child(flashcard.id)
                    .PutAsync(flashcard);
    
                await LoadDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    
        /// <summary>
        /// Loads flashcard data from Firebase and applies current filters and sorting.
        /// </summary>
        private async Task LoadDataAsync()
        {
            try
            {
                var data = await firebaseClient
                    .Child("flashcards")
                    .OnceAsync<FlashcardItem>();
    
                allFlashcards = data.Select(d => new FlashcardItem
                {
                    id = d.Key,
                    title = d.Object.title,
                    category = string.IsNullOrWhiteSpace(d.Object.category) ? "Uncategorized" : d.Object.category,
                    content = d.Object.content,
                    favorite = d.Object.favorite,
                    pinned = d.Object.pinned,
                    timestamp = d.Object.timestamp,
                    backgroundColor = d.Object.backgroundColor
                }).ToList();
    
                ApplyFiltersAndSort();
    
                // After data is loaded, populate the ContextMenuStrip
                PopulateColumnContextMenu();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    
        private void ApplyFiltersAndSort()
        {
            // Start with all flashcards
            IEnumerable<FlashcardItem> filtered = allFlashcards;
    
            // Apply Favorites filter
            if (chkFilterFavorites.Checked)
            {
                filtered = filtered.Where(f => f.favorite);
            }
    
            // Apply Pinned filter
            if (chkFilterPinned.Checked)
            {
                filtered = filtered.Where(f => f.pinned);
            }
    
            // Apply Search filter
            if (!string.IsNullOrWhiteSpace(currentSearchTerm))
            {
                filtered = filtered.Where(f =>
                    f.title.ToLower().Contains(currentSearchTerm) ||
                    f.category.ToLower().Contains(currentSearchTerm) ||
                    f.content.ToLower().Contains(currentSearchTerm));
            }
    
            // Convert to List for further operations
            List<FlashcardItem> filteredList = filtered.ToList();
    
            // Check if the filtered list is empty
            if (filteredList.Count == 0)
            {
                // Determine which filter caused the empty list
                bool isFavoritesFilterActive = chkFilterFavorites.Checked;
                bool isPinnedFilterActive = chkFilterPinned.Checked;
    
                // If both filters are active, we need to determine which one caused the issue
                if (isFavoritesFilterActive && isPinnedFilterActive)
                {
                    // Temporarily disable one filter to check if the list is still empty
                    chkFilterFavorites.Checked = false;
                    ApplyFiltersAndSort();
                    return;
                }
                else if (isFavoritesFilterActive)
                {
                    chkFilterFavorites.Checked = false;
                    MessageBox.Show("No favorites found. Filter has been reset.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (isPinnedFilterActive)
                {
                    chkFilterPinned.Checked = false;
                    MessageBox.Show("No pinned items found. Filter has been reset.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("No flashcards match the current filters.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
    
                // Reload the entire list
                filteredList = allFlashcards.ToList();
            }
    
            // Apply Sorting
            if (!string.IsNullOrEmpty(currentSortColumn))
            {
                if (sortAscending)
                {
                    switch (currentSortColumn)
                    {
                        case "title":
                            filteredList = filteredList.OrderBy(f => f.title).ToList();
                            break;
                        case "timestamp":
                            filteredList = filteredList.OrderBy(f => f.timestamp).ToList();
                            break;
                            // Add more cases if you implement sorting on other columns
                    }
                }
                else
                {
                    switch (currentSortColumn)
                    {
                        case "title":
                            filteredList = filteredList.OrderByDescending(f => f.title).ToList();
                            break;
                        case "timestamp":
                            filteredList = filteredList.OrderByDescending(f => f.timestamp).ToList();
                            break;
                            // Add more cases if you implement sorting on other columns
                    }
                }
            }
    
            UpdateDataGridView(filteredList);
        }
    
    
        /// <summary>
        /// Updates the DataGridView with the provided list of flashcards.
        /// </summary>
        private void UpdateDataGridView(List<FlashcardItem> flashcards)
        {
            dataGridView.DataSource = null;
            dataGridView.Columns.Clear();
    
            if (flashcards.Any())
            {
                dataGridView.AutoGenerateColumns = false;
    
                // Define DataGridView columns
    
                // ID Column - Hidden
                var idColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "id",
                    HeaderText = "ID",
                    Visible = false
                };
                dataGridView.Columns.Add(idColumn);
    
                // Title Column
                var titleColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "title",
                    HeaderText = "Title",
                    Name = "title",
                    SortMode = DataGridViewColumnSortMode.Programmatic
                };
                dataGridView.Columns.Add(titleColumn);
    
                // Category Column
                var categoryColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "category",
                    HeaderText = "Category",
                    Name = "category",
                    SortMode = DataGridViewColumnSortMode.NotSortable
                };
                dataGridView.Columns.Add(categoryColumn);
    
                // Content Column
                var contentColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "content",
                    HeaderText = "Content",
                    Name = "content",
                    SortMode = DataGridViewColumnSortMode.NotSortable
                };
                dataGridView.Columns.Add(contentColumn);
    
                // Favorite Column (Checkbox)
                var favoriteColumn = new DataGridViewCheckBoxColumn
                {
                    DataPropertyName = "favorite",
                    HeaderText = "Favorite",
                    Name = "favorite",
                    SortMode = DataGridViewColumnSortMode.Automatic
                };
                dataGridView.Columns.Add(favoriteColumn);
    
                // Pinned Column (Checkbox)
                var pinnedColumn = new DataGridViewCheckBoxColumn
                {
                    DataPropertyName = "pinned",
                    HeaderText = "Pinned",
                    Name = "pinned",
                    SortMode = DataGridViewColumnSortMode.Automatic
                };
                dataGridView.Columns.Add(pinnedColumn);
    
                // Timestamp Column
                var timestampColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "timestamp",
                    HeaderText = "Timestamp",
                    Name = "timestamp",
                    SortMode = DataGridViewColumnSortMode.Programmatic
                };
                dataGridView.Columns.Add(timestampColumn);
    
                // BackgroundColor Column
                var backgroundColorColumn = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "backgroundColor",
                    HeaderText = "Background Color",
                    Name = "backgroundColor",
                    SortMode = DataGridViewColumnSortMode.NotSortable
                };
                dataGridView.Columns.Add(backgroundColorColumn);
    
                dataGridView.DataSource = flashcards;
            }
            else
            {
                // If no flashcards match the filters, display a message
                var messageColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "Message",
                    Name = "Message",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                };
                dataGridView.Columns.Add(messageColumn);
                dataGridView.Rows.Add("No flashcards found.");
            }
    
            // Restore column visibility state
            RestoreColumnVisibilityState();
    
            // Update the status label with the count
            statusLabel.Text = $"Total Items: {flashcards.Count}";
        }
    
        /// <summary>
        /// Populates the ContextMenuStrip with the current DataGridView columns.
        /// Ensures no duplicate menu items are added.
        /// </summary>
        private void PopulateColumnContextMenu()
        {
            columnContextMenu.Items.Clear(); // Clear existing items to prevent duplication
    
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                // Skip hidden or irrelevant columns if necessary
                // For example, you might want to skip the "ID" column
                if (column.Name == "ID") continue;
    
                // Create a ToolStripMenuItem for the column
                var menuItem = new ToolStripMenuItem(column.HeaderText)
                {
                    Checked = column.Visible,
                    CheckOnClick = true,
                    Tag = column // Store the column in Tag for reference
                };
                menuItem.CheckedChanged += ColumnMenuItem_CheckedChanged;
    
                // Add the menu item to the ContextMenuStrip
                columnContextMenu.Items.Add(menuItem);
            }
        }
    
        /// <summary>
        /// Handles the CheckedChanged event of ContextMenuStrip items to toggle column visibility.
        /// </summary>
        private void ColumnMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menuItem && menuItem.Tag is DataGridViewColumn column)
            {
                column.Visible = menuItem.Checked;
                columnVisibilityState[column.Name] = column.Visible; // Update the visibility state
            }
        }
    
        /// <summary>
        /// Shows the ContextMenuStrip when the user right-clicks on a column header.
        /// </summary>
        private void DataGridView_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var hitTestInfo = dataGridView.HitTest(e.X, e.Y);
                if (hitTestInfo.Type == DataGridViewHitTestType.ColumnHeader)
                {
                    // Show the ContextMenuStrip at the mouse position
                    columnContextMenu.Show(dataGridView, new Point(e.X, e.Y));
                }
            }
        }
    
        /// <summary>
        /// Adds a new flashcard to the Firebase database.
        /// </summary>
        private async void AddData()
        {
            var newFlashcard = CreateFlashcardFromInputs();
            if (newFlashcard != null)
            {
                try
                {
                    var response = await firebaseClient
                        .Child("flashcards")
                        .PostAsync(newFlashcard);
    
                    newFlashcard.id = response.Key;
                    await LoadDataAsync();
                    ClearInputs();
                    MessageBox.Show("Flashcard added successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error adding flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    
        /// <summary>
        /// Updates the selected flashcard in the Firebase database.
        /// </summary>
        private async void UpdateData()
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem;
                var updatedFlashcard = CreateFlashcardFromInputs();
                if (updatedFlashcard != null)
                {
                    updatedFlashcard.id = selectedFlashcard.id;
                    updatedFlashcard.timestamp = selectedFlashcard.timestamp; // Zaman damgasını koru
                    try
                    {
                        await firebaseClient
                            .Child("flashcards")
                            .Child(selectedFlashcard.id)
                            .PutAsync(updatedFlashcard);
    
                        await LoadDataAsync();
                        ClearInputs();
                        MessageBox.Show("Flashcard updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("Please select a flashcard to update.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    
        /// <summary>
        /// Deletes selected flashcards from the Firebase database.
        /// </summary>
        private async void DeleteData()
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                int selectedCount = dataGridView.SelectedRows.Count;
                var confirmResult = MessageBox.Show($"Are you sure you want to delete {selectedCount} flashcard(s)?",
                                                    "Confirm Delete",
                                                    MessageBoxButtons.YesNo,
                                                    MessageBoxIcon.Question);
                if (confirmResult == DialogResult.Yes)
                {
                    try
                    {
                        // Create a list of delete tasks
                        var deleteTasks = dataGridView.SelectedRows
                            .Cast<DataGridViewRow>()
                            .Select(row =>
                            {
                                var flashcard = (FlashcardItem)row.DataBoundItem;
                                return firebaseClient.Child("flashcards").Child(flashcard.id).DeleteAsync();
                            })
                            .ToList();
    
                        // Execute all delete tasks in parallel
                        await Task.WhenAll(deleteTasks);
    
                        // Clear inputs and reload data
                        ClearInputs();
                        await LoadDataAsync();
    
                        MessageBox.Show($"{selectedCount} flashcard(s) deleted successfully!",
                                        "Success",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error deleting flashcards: {ex.Message}",
                                        "Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("Please select one or more flashcards to delete.",
                                "No Selection",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
        }
    
        /// <summary>
        /// Creates a FlashcardItem object from the input fields.
        /// </summary>
        private FlashcardItem CreateFlashcardFromInputs()
        {
            string title = txtTitle.Text == "Title" ? "" : txtTitle.Text.Trim();
            string category = txtCategory.Text == "Category" ? "Uncategorized" : txtCategory.Text.Trim();
            string content = txtContent.Text == "Content" ? "" : txtContent.Text.Trim();
            string backgroundColor = txtBackgroundColor.Text == "Background Color" ? "" : txtBackgroundColor.Text.Trim();
    
            if (string.IsNullOrEmpty(title))
            {
                MessageBox.Show("Title cannot be empty.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }
    
            return new FlashcardItem
            {
                title = title,
                category = category,
                content = content,
                favorite = chkFavorite.Checked,
                pinned = chkPinned.Checked,
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                backgroundColor = backgroundColor
            };
        }
    
        /// <summary>
        /// Clears the input fields and resets placeholders.
        /// </summary>
        private void ClearInputs()
        {
            txtTitle.Text = "Title";
            txtTitle.ForeColor = Color.Gray;
            txtCategory.Text = "Category";
            txtCategory.ForeColor = Color.Gray;
            txtContent.Text = "Content";
            txtContent.ForeColor = Color.Gray;
            txtBackgroundColor.Text = "Background Color";
            txtBackgroundColor.ForeColor = Color.Gray;
            chkFavorite.Checked = false;
            chkPinned.Checked = false;
        }
    
        /// <summary>
        /// Handles the selection change in the DataGridView to populate the input fields.
        /// </summary>
        private void DataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem;
                txtTitle.Text = selectedFlashcard.title;
                txtTitle.ForeColor = Color.Black;
                txtCategory.Text = selectedFlashcard.category;
                txtCategory.ForeColor = Color.Black;
                txtContent.Text = selectedFlashcard.content;
                txtContent.ForeColor = Color.Black;
                txtBackgroundColor.Text = selectedFlashcard.backgroundColor;
                txtBackgroundColor.ForeColor = Color.Black;
                chkFavorite.Checked = selectedFlashcard.favorite;
                chkPinned.Checked = selectedFlashcard.pinned;
            }
        }
    
        /// <summary>
        /// Sets up a real-time listener to Firebase to update data upon changes.
        /// </summary>
        private void RealTimeListener()
        {
            firebaseClient
                .Child("flashcards")
                .AsObservable<FlashcardItem>()
                .Subscribe(d =>
                {
                    Invoke((Action)(async () => await LoadDataAsync()));
                });
        }
    
        /// <summary>
        /// Handles the Search button click to apply search criteria.
        /// </summary>
        private void SearchData()
        {
            string searchText = txtSearch.Text;
            if (string.IsNullOrWhiteSpace(searchText) || searchText == "Search...")
            {
                currentSearchTerm = "";
            }
            else
            {
                currentSearchTerm = searchText.ToLower();
            }
    
            ApplyFiltersAndSort();
        }
    
        /// <summary>
        /// Clears the search input and resets search filter.
        /// </summary>
        private void ClearSearch()
        {
            txtSearch.Text = "Search...";
            txtSearch.ForeColor = Color.Gray;
            currentSearchTerm = "";
            ApplyFiltersAndSort();
        }
    
        /// <summary>
        /// Formats the timestamp column to display human-readable dates.
        /// </summary>
        private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView.Columns[e.ColumnIndex].Name == "timestamp")
            {
                if (e.Value != null && long.TryParse(e.Value.ToString(), out long timestamp))
                {
                    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
                    DateTime dateTime = dateTimeOffset.ToOffset(TimeSpan.FromHours(3)).DateTime; // Türkiye saati için UTC+3
                    e.Value = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    e.FormattingApplied = true;
                }
            }
        }
    
        /// <summary>
        /// Handles the column header click event to apply sorting.
        /// </summary>
        private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            string columnName = dataGridView.Columns[e.ColumnIndex].Name;
    
            // Only allow sorting on 'title' and 'timestamp' columns
            if (columnName == "title" || columnName == "timestamp")
            {
                // Toggle sort direction if the same column is clicked
                if (currentSortColumn == columnName)
                {
                    sortAscending = !sortAscending;
                }
                else
                {
                    // Default to ascending if a new column is clicked
                    currentSortColumn = columnName;
                    sortAscending = true;
                }
    
                // Apply sorting and refresh DataGridView
                ApplyFiltersAndSort();
    
                // Reset sort glyphs on all columns
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    column.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
    
                // Set sort glyph on the sorted column
                dataGridView.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = sortAscending ? SortOrder.Ascending : SortOrder.Descending;
            }
        }
    
        /// <summary>
        /// Handles the CheckedChanged events for filtering CheckBoxes.
        /// </summary>
        private void FilterCheckBoxChanged(object sender, EventArgs e)
        {
            ApplyFiltersAndSort();
        }
    
        /// <summary>
        /// Restores the column visibility state from the stored dictionary.
        /// </summary>
        private void RestoreColumnVisibilityState()
        {
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                if (columnVisibilityState.TryGetValue(column.Name, out bool isVisible))
                {
                    column.Visible = isVisible;
                }
            }
        }
    }
    
    /// <summary>
    /// Represents a Flashcard item.
    /// </summary>
    public class FlashcardItem
    {
        public string id { get; set; }
        public string category { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public bool favorite { get; set; }
        public bool pinned { get; set; }
        public long timestamp { get; set; }
        public string backgroundColor { get; set; }
    }
    

    }

  2. Assistant

    Merhaba,

    İstekleriniz doğrultusunda kodu güncelledim:

    • MenuStrip pencerenin üst kısmına taşındı ve DockStyle.Top ile üstte konumlandırıldı.
    • DataGridView menünün hemen altına yerleştirildi.
    • Kontroller arasındaki mesafeler, standart Windows Form arayüzündeki gibi ayarlandı.
    • Kodun fonksiyonelliğini ve içeriğini değiştirmedim.

    İşte güncellenmiş kodunuz:

    using System;
    using System.Windows.Forms;
    using Firebase.Database;
    using Firebase.Database.Query;
    using FirebaseAdmin;
    using Google.Apis.Auth.OAuth2;
    using System.Threading.Tasks;
    using System.Linq;
    using System.Drawing;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    
    namespace Flashcard
    {
        public partial class MainForm : Form
        {
            // Firebase client
            private FirebaseClient firebaseClient;
    
            // UI Controls
            private DataGridView dataGridView;
            private TextBox txtTitle, txtCategory, txtContent, txtBackgroundColor, txtSearch;
            private CheckBox chkFavorite, chkPinned;
            private CheckBox chkFilterFavorites, chkFilterPinned; // Filtering CheckBoxes
            private Button btnAdd, btnUpdate, btnDelete, btnSearch, btnClear;
            private StatusStrip statusStrip;
            private ToolStripStatusLabel statusLabel;
    
            // **Yeni Eklenen Kontroller**
            private MenuStrip menuStrip; // Menü Çubuğu
            private ToolStripMenuItem fileMenuItem, themeMenuItem; // Menü Öğeleri
            private ToolStripMenuItem saveAsMenuItem, lightModeMenuItem, darkModeMenuItem; // Alt Menü Öğeleri
    
            // ContextMenuStrip for column visibility
            private ContextMenuStrip columnContextMenu;
    
            // Sorting state
            private string currentSortColumn = "";
            private bool sortAscending = true;
    
            // Data storage
            private List<FlashcardItem> allFlashcards = new List<FlashcardItem>();
    
            // Current search term
            private string currentSearchTerm = "";
    
            // Dictionary to store column visibility state
            private Dictionary<string, bool> columnVisibilityState = new Dictionary<string, bool>();
    
            public MainForm()
            {
                InitializeComponent();
                InitializeFirebase();
                InitializeUI();
            }
    
            /// <summary>
            /// Initializes Firebase connection using the provided JSON credentials.
            /// </summary>
            private void InitializeFirebase()
            {
                var path = "flashcard-e7f47-firebase-adminsdk-om656-e70a5506c2.json";
                var credential = GoogleCredential.FromFile(path);
    
                // Check if FirebaseApp is already created to prevent duplicate initialization
                if (FirebaseApp.DefaultInstance == null)
                {
                    FirebaseApp.Create(new AppOptions
                    {
                        Credential = credential
                    });
                }
    
                firebaseClient = new FirebaseClient("https://flashcard-e7f47-default-rtdb.europe-west1.firebasedatabase.app/");
            }
    
            /// <summary>
            /// Sets up the user interface components.
            /// </summary>
            private void InitializeUI()
            {
                this.Size = new Size(1000, 800);
                this.Text = "Flashcard Application";
    
                // **MenuStrip Oluşturma**
                menuStrip = new MenuStrip
                {
                    Dock = DockStyle.Top // MenuStrip'i üstte konumlandır
                };
    
                // **File Menu**
                fileMenuItem = new ToolStripMenuItem("File");
                saveAsMenuItem = new ToolStripMenuItem("Save As");
                saveAsMenuItem.Click += SaveAsMenuItem_Click; // Event Handler
                fileMenuItem.DropDownItems.Add(saveAsMenuItem);
    
                // **Theme Menu**
                themeMenuItem = new ToolStripMenuItem("Theme");
                lightModeMenuItem = new ToolStripMenuItem("Light Mode");
                darkModeMenuItem = new ToolStripMenuItem("Dark Mode");
                lightModeMenuItem.Click += LightModeMenuItem_Click; // Event Handler
                darkModeMenuItem.Click += DarkModeMenuItem_Click; // Event Handler
                themeMenuItem.DropDownItems.Add(lightModeMenuItem);
                themeMenuItem.DropDownItems.Add(darkModeMenuItem);
    
                // **MenuStrip'e Menüleri Ekleme**
                menuStrip.Items.Add(fileMenuItem);
                menuStrip.Items.Add(themeMenuItem);
    
                // **Form'a MenuStrip'i Ekleme**
                this.MainMenuStrip = menuStrip;
                Controls.Add(menuStrip); // MenuStrip'i ilk olarak ekliyoruz
    
                // Initialize DataGridView
                dataGridView = new DataGridView
                {
                    Height = 400,
                    Left = 0,
                    Top = menuStrip.Bottom, // DataGridView'i MenuStrip'in altına yerleştir
                    Width = this.ClientSize.Width,
                    Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right,
                    AllowUserToAddRows = false,
                    AllowUserToDeleteRows = false,
                    ReadOnly = false,
                    SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                    MultiSelect = true,
                    AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                    ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
                };
    
                dataGridView.SelectionChanged += DataGridView_SelectionChanged;
                dataGridView.CellContentClick += DataGridView_CellContentClick;
                dataGridView.CellFormatting += DataGridView_CellFormatting;
                dataGridView.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick; // For sorting
                Controls.Add(dataGridView);
    
                // Kontroller arası standart Windows Forms arayüzündeki gibi mesafeler
                int labelLeft = 10;
                int textBoxLeft = 150;
                int startTop = dataGridView.Bottom + 6; // DataGridView'in hemen altından başla
                int textBoxWidth = 300;
                int textBoxHeight = 25;
                int verticalSpacing = 6; // Kontroller arası boşluk
    
                int currentTop = startTop;
    
                // Etiketleri ve Metin Kutularını Oluştur
    
                // Category
                CreateLabel("Category:", labelLeft, currentTop);
                txtCategory = CreateTextBox("Category", textBoxLeft, currentTop, textBoxWidth);
                currentTop += textBoxHeight + verticalSpacing;
    
                // Title
                CreateLabel("Title:", labelLeft, currentTop);
                txtTitle = CreateTextBox("Title", textBoxLeft, currentTop, textBoxWidth);
                currentTop += textBoxHeight + verticalSpacing;
    
                // Content
                CreateLabel("Content:", labelLeft, currentTop);
                txtContent = CreateTextBox("Content", textBoxLeft, currentTop, textBoxWidth);
                currentTop += textBoxHeight + verticalSpacing;
    
                // Background Color
                CreateLabel("Background Color:", labelLeft, currentTop);
                txtBackgroundColor = CreateTextBox("Background Color", textBoxLeft, currentTop, textBoxWidth);
                currentTop += textBoxHeight + verticalSpacing;
    
                // İşlevsel CheckBox'lar
                chkFavorite = new CheckBox { Text = "Favorite", Top = currentTop, Left = textBoxLeft, Width = 80 };
                Controls.Add(chkFavorite);
    
                chkPinned = new CheckBox { Text = "Pinned", Top = currentTop, Left = textBoxLeft + 90, Width = 80 };
                Controls.Add(chkPinned);
    
                currentTop += chkFavorite.Height + verticalSpacing;
    
                // Butonları Yatay Olarak Hizala
                int buttonTop = currentTop + 10; // Biraz boşluk ekle
                int buttonLeft = labelLeft;
    
                btnAdd = CreateButton("Add", buttonLeft, buttonTop, 100);
                buttonLeft += 110;
    
                btnUpdate = CreateButton("Update", buttonLeft, buttonTop, 100);
                buttonLeft += 110;
    
                btnDelete = CreateButton("Delete", buttonLeft, buttonTop, 100);
    
                // Arama Metin Kutusu ve Butonları
                int searchLeft = textBoxLeft + textBoxWidth + 50;
                txtSearch = CreateTextBox("Search...", searchLeft, dataGridView.Bottom + 10, 200);
                btnSearch = CreateButton("Search", searchLeft, txtSearch.Bottom + 5, 100);
                btnClear = CreateButton("Clear", searchLeft + 110, txtSearch.Bottom + 5, 90);
    
                // Filtreleme CheckBox'ları
                chkFilterFavorites = new CheckBox
                {
                    Text = "Show Favorites",
                    Top = btnSearch.Bottom + 10,
                    Left = searchLeft,
                    Width = 120
                };
                chkFilterFavorites.CheckedChanged += FilterCheckBoxChanged;
                Controls.Add(chkFilterFavorites);
    
                chkFilterPinned = new CheckBox
                {
                    Text = "Show Pinned",
                    Top = btnSearch.Bottom + 10,
                    Left = searchLeft + 130,
                    Width = 120
                };
                chkFilterPinned.CheckedChanged += FilterCheckBoxChanged;
                Controls.Add(chkFilterPinned);
    
                // StatusStrip
                statusStrip = new StatusStrip();
                statusLabel = new ToolStripStatusLabel();
                statusStrip.Items.Add(statusLabel);
                Controls.Add(statusStrip);
    
                // ContextMenuStrip for column visibility
                columnContextMenu = new ContextMenuStrip();
                // Note: We'll populate the ContextMenuStrip after loading data to ensure column information is available
    
                // Assign the MouseUp event to show the ContextMenuStrip on right-click
                dataGridView.MouseUp += DataGridView_MouseUp;
    
                // Event Handler for Form Load
                this.Load += MainForm_Load;
            }
    
            // Yeni bir CreateLabel metodu ekliyoruz
            private Label CreateLabel(string text, int left, int top)
            {
                Label label = new Label
                {
                    Text = text,
                    Left = left,
                    Top = top,
                    AutoSize = true
                };
                Controls.Add(label);
                return label;
            }
    
            /// <summary>
            /// Handles the Form Load event to initially load data and start real-time listener.
            /// </summary>
            private async void MainForm_Load(object sender, EventArgs e)
            {
                await LoadDataAsync();
                // RealTimeListener(); // Optional: Uncomment if you want real-time updates
            }
    
            /// <summary>
            /// Creates a TextBox with placeholder text and associated event handlers.
            /// </summary>
            private TextBox CreateTextBox(string placeholder, int left, int top, int width)
            {
                TextBox textBox = new TextBox
                {
                    Left = left,
                    Top = top,
                    Width = width,
                    Text = placeholder,
                    ForeColor = Color.Gray
                };
                textBox.GotFocus += (sender, e) =>
                {
                    if (textBox.Text == placeholder)
                    {
                        textBox.Text = "";
                        textBox.ForeColor = Color.Black;
                    }
                };
                textBox.LostFocus += (sender, e) =>
                {
                    if (string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        textBox.Text = placeholder;
                        textBox.ForeColor = Color.Gray;
                    }
                };
                Controls.Add(textBox);
                return textBox;
            }
    
            /// <summary>
            /// Creates a Button with specified properties and assigns click event.
            /// </summary>
            private Button CreateButton(string text, int left, int top, int width)
            {
                Button button = new Button
                {
                    Text = text,
                    Left = left,
                    Top = top,
                    Width = width
                };
                button.Click += (sender, e) => ButtonClick(text);
                Controls.Add(button);
                return button;
            }
    
            /// <summary>
            /// Handles button click events by identifying the button text.
            /// </summary>
            private void ButtonClick(string buttonText)
            {
                switch (buttonText)
                {
                    case "Add":
                        AddData();
                        break;
                    case "Update":
                        UpdateData();
                        break;
                    case "Delete":
                        DeleteData();
                        break;
                    case "Search":
                        SearchData();
                        break;
                    case "Clear":
                        ClearSearch();
                        break;
                }
            }
    
            /// <summary>
            /// Handles the "Save As" menu item click to save data in selected format.
            /// </summary>
            private void SaveAsMenuItem_Click(object sender, EventArgs e)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Filter = "CSV files (*.csv)|*.csv|TSV files (*.tsv)|*.tsv|Text files (*.txt)|*.txt",
                    Title = "Save As"
                };
    
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string extension = Path.GetExtension(saveFileDialog.FileName).ToLower();
                        // DataGridView'den verileri al
                        var data = (List<FlashcardItem>)dataGridView.DataSource;
    
                        // Verileri seçilen formata göre kaydet
                        switch (extension)
                        {
                            case ".csv":
                                SaveDataAsCsv(data, saveFileDialog.FileName, ',');
                                break;
                            case ".tsv":
                                SaveDataAsCsv(data, saveFileDialog.FileName, '\t');
                                break;
                            case ".txt":
                                SaveDataAsTxt(data, saveFileDialog.FileName);
                                break;
                            default:
                                MessageBox.Show("Unsupported file format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                        }
    
                        MessageBox.Show("Data saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error saving data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
    
            /// <summary>
            /// Saves data as CSV or TSV file.
            /// </summary>
            private void SaveDataAsCsv(List<FlashcardItem> data, string filePath, char delimiter)
            {
                StringBuilder sb = new StringBuilder();
    
                // Başlık satırı
                sb.AppendLine(string.Join(delimiter.ToString(), "Category", "Title", "Content", "Favorite", "Pinned", "Timestamp", "BackgroundColor"));
    
                foreach (var item in data)
                {
                    string[] fields = new string[]
                    {
                        EscapeCsvField(item.category),
                        EscapeCsvField(item.title),
                        EscapeCsvField(item.content),
                        item.favorite.ToString(),
                        item.pinned.ToString(),
                        item.timestamp.ToString(),
                        EscapeCsvField(item.backgroundColor)
                    };
    
                    sb.AppendLine(string.Join(delimiter.ToString(), fields));
                }
    
                File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
            }
    
            /// <summary>
            /// Escapes CSV fields containing delimiter or quotes.
            /// </summary>
            private string EscapeCsvField(string field)
            {
                if (field.Contains(",") || field.Contains("\"") || field.Contains("\r") || field.Contains("\n"))
                {
                    return $"\"{field.Replace("\"", "\"\"")}\"";
                }
                else
                {
                    return field;
                }
            }
    
            /// <summary>
            /// Saves data as TXT file.
            /// </summary>
            private void SaveDataAsTxt(List<FlashcardItem> data, string filePath)
            {
                StringBuilder sb = new StringBuilder();
    
                foreach (var item in data)
                {
                    sb.AppendLine($"Category: {item.category}");
                    sb.AppendLine($"Title: {item.title}");
                    sb.AppendLine($"Content: {item.content}");
                    sb.AppendLine($"Favorite: {item.favorite}");
                    sb.AppendLine($"Pinned: {item.pinned}");
                    sb.AppendLine($"Timestamp: {item.timestamp}");
                    sb.AppendLine($"BackgroundColor: {item.backgroundColor}");
                    sb.AppendLine(new string('-', 50));
                }
    
                File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
            }
    
            /// <summary>
            /// Handles the Light Mode menu item click.
            /// </summary>
            private void LightModeMenuItem_Click(object sender, EventArgs e)
            {
                SetTheme(Color.White, Color.Black);
            }
    
            /// <summary>
            /// Handles the Dark Mode menu item click.
            /// </summary>
            private void DarkModeMenuItem_Click(object sender, EventArgs e)
            {
                SetTheme(Color.FromArgb(45, 45, 48), Color.White);
            }
    
            /// <summary>
            /// Sets the application's theme colors.
            /// </summary>
            private void SetTheme(Color backColor, Color foreColor)
            {
                this.BackColor = backColor;
                this.ForeColor = foreColor;
    
                foreach (Control control in this.Controls)
                {
                    SetControlTheme(control, backColor, foreColor);
                }
    
                // DataGridView renklerini ayarla
                dataGridView.BackgroundColor = backColor;
                dataGridView.DefaultCellStyle.BackColor = backColor;
                dataGridView.DefaultCellStyle.ForeColor = foreColor;
                dataGridView.ColumnHeadersDefaultCellStyle.BackColor = backColor;
                dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = foreColor;
                dataGridView.RowHeadersDefaultCellStyle.BackColor = backColor;
                dataGridView.RowHeadersDefaultCellStyle.ForeColor = foreColor;
                dataGridView.GridColor = foreColor;
            }
    
            /// <summary>
            /// Recursively sets theme colors for controls.
            /// </summary>
            private void SetControlTheme(Control control, Color backColor, Color foreColor)
            {
                control.BackColor = backColor;
                control.ForeColor = foreColor;
    
                if (control.HasChildren)
                {
                    foreach (Control child in control.Controls)
                    {
                        SetControlTheme(child, backColor, foreColor);
                    }
                }
            }
    
            /// <summary>
            /// Handles CellContentClick events for CheckBox columns to toggle favorite and pinned statuses.
            /// </summary>
            private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {
                if (e.RowIndex >= 0 && (dataGridView.Columns[e.ColumnIndex].Name == "favorite" || dataGridView.Columns[e.ColumnIndex].Name == "pinned"))
                {
                    var flashcard = (FlashcardItem)dataGridView.Rows[e.RowIndex].DataBoundItem;
                    bool newValue = !(bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
    
                    if (dataGridView.Columns[e.ColumnIndex].Name == "favorite")
                    {
                        flashcard.favorite = newValue;
                    }
                    else
                    {
                        flashcard.pinned = newValue;
                    }
    
                    _ = UpdateFlashcardInDatabase(flashcard);
                }
            }
    
            /// <summary>
            /// Updates a flashcard in the Firebase database.
            /// </summary>
            private async Task UpdateFlashcardInDatabase(FlashcardItem flashcard)
            {
                try
                {
                    await firebaseClient
                        .Child("flashcards")
                        .Child(flashcard.id)
                        .PutAsync(flashcard);
    
                    await LoadDataAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            /// <summary>
            /// Loads flashcard data from Firebase and applies current filters and sorting.
            /// </summary>
            private async Task LoadDataAsync()
            {
                try
                {
                    var data = await firebaseClient
                        .Child("flashcards")
                        .OnceAsync<FlashcardItem>();
    
                    allFlashcards = data.Select(d => new FlashcardItem
                    {
                        id = d.Key,
                        title = d.Object.title,
                        category = string.IsNullOrWhiteSpace(d.Object.category) ? "Uncategorized" : d.Object.category,
                        content = d.Object.content,
                        favorite = d.Object.favorite,
                        pinned = d.Object.pinned,
                        timestamp = d.Object.timestamp,
                        backgroundColor = d.Object.backgroundColor
                    }).ToList();
    
                    ApplyFiltersAndSort();
    
                    // After data is loaded, populate the ContextMenuStrip
                    PopulateColumnContextMenu();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error loading data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            private void ApplyFiltersAndSort()
            {
                // Start with all flashcards
                IEnumerable<FlashcardItem> filtered = allFlashcards;
    
                // Apply Favorites filter
                if (chkFilterFavorites.Checked)
                {
                    filtered = filtered.Where(f => f.favorite);
                }
    
                // Apply Pinned filter
                if (chkFilterPinned.Checked)
                {
                    filtered = filtered.Where(f => f.pinned);
                }
    
                // Apply Search filter
                if (!string.IsNullOrWhiteSpace(currentSearchTerm))
                {
                    filtered = filtered.Where(f =>
                        f.title.ToLower().Contains(currentSearchTerm) ||
                        f.category.ToLower().Contains(currentSearchTerm) ||
                        f.content.ToLower().Contains(currentSearchTerm));
                }
    
                // Convert to List for further operations
                List<FlashcardItem> filteredList = filtered.ToList();
    
                // Check if the filtered list is empty
                if (filteredList.Count == 0)
                {
                    // Determine which filter caused the empty list
                    bool isFavoritesFilterActive = chkFilterFavorites.Checked;
                    bool isPinnedFilterActive = chkFilterPinned.Checked;
    
                    // If both filters are active, we need to determine which one caused the issue
                    if (isFavoritesFilterActive && isPinnedFilterActive)
                    {
                        // Temporarily disable one filter to check if the list is still empty
                        chkFilterFavorites.Checked = false;
                        ApplyFiltersAndSort();
                        return;
                    }
                    else if (isFavoritesFilterActive)
                    {
                        chkFilterFavorites.Checked = false;
                        MessageBox.Show("No favorites found. Filter has been reset.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (isPinnedFilterActive)
                    {
                        chkFilterPinned.Checked = false;
                        MessageBox.Show("No pinned items found. Filter has been reset.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("No flashcards match the current filters.", "No Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
    
                    // Reload the entire list
                    filteredList = allFlashcards.ToList();
                }
    
                // Apply Sorting
                if (!string.IsNullOrEmpty(currentSortColumn))
                {
                    if (sortAscending)
                    {
                        switch (currentSortColumn)
                        {
                            case "title":
                                filteredList = filteredList.OrderBy(f => f.title).ToList();
                                break;
                            case "timestamp":
                                filteredList = filteredList.OrderBy(f => f.timestamp).ToList();
                                break;
                                // Add more cases if you implement sorting on other columns
                        }
                    }
                    else
                    {
                        switch (currentSortColumn)
                        {
                            case "title":
                                filteredList = filteredList.OrderByDescending(f => f.title).ToList();
                                break;
                            case "timestamp":
                                filteredList = filteredList.OrderByDescending(f => f.timestamp).ToList();
                                break;
                                // Add more cases if you implement sorting on other columns
                        }
                    }
                }
    
                UpdateDataGridView(filteredList);
            }
    
            /// <summary>
            /// Updates the DataGridView with the provided list of flashcards.
            /// </summary>
            private void UpdateDataGridView(List<FlashcardItem> flashcards)
            {
                dataGridView.DataSource = null;
                dataGridView.Columns.Clear();
    
                if (flashcards.Any())
                {
                    dataGridView.AutoGenerateColumns = false;
    
                    // Define DataGridView columns
    
                    // ID Column - Hidden
                    var idColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "id",
                        HeaderText = "ID",
                        Visible = false
                    };
                    dataGridView.Columns.Add(idColumn);
    
                    // Title Column
                    var titleColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "title",
                        HeaderText = "Title",
                        Name = "title",
                        SortMode = DataGridViewColumnSortMode.Programmatic
                    };
                    dataGridView.Columns.Add(titleColumn);
    
                    // Category Column
                    var categoryColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "category",
                        HeaderText = "Category",
                        Name = "category",
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    dataGridView.Columns.Add(categoryColumn);
    
                    // Content Column
                    var contentColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "content",
                        HeaderText = "Content",
                        Name = "content",
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    dataGridView.Columns.Add(contentColumn);
    
                    // Favorite Column (Checkbox)
                    var favoriteColumn = new DataGridViewCheckBoxColumn
                    {
                        DataPropertyName = "favorite",
                        HeaderText = "Favorite",
                        Name = "favorite",
                        SortMode = DataGridViewColumnSortMode.Automatic
                    };
                    dataGridView.Columns.Add(favoriteColumn);
    
                    // Pinned Column (Checkbox)
                    var pinnedColumn = new DataGridViewCheckBoxColumn
                    {
                        DataPropertyName = "pinned",
                        HeaderText = "Pinned",
                        Name = "pinned",
                        SortMode = DataGridViewColumnSortMode.Automatic
                    };
                    dataGridView.Columns.Add(pinnedColumn);
    
                    // Timestamp Column
                    var timestampColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "timestamp",
                        HeaderText = "Timestamp",
                        Name = "timestamp",
                        SortMode = DataGridViewColumnSortMode.Programmatic
                    };
                    dataGridView.Columns.Add(timestampColumn);
    
                    // BackgroundColor Column
                    var backgroundColorColumn = new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "backgroundColor",
                        HeaderText = "Background Color",
                        Name = "backgroundColor",
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    dataGridView.Columns.Add(backgroundColorColumn);
    
                    dataGridView.DataSource = flashcards;
                }
                else
                {
                    // If no flashcards match the filters, display a message
                    var messageColumn = new DataGridViewTextBoxColumn
                    {
                        HeaderText = "Message",
                        Name = "Message",
                        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                    };
                    dataGridView.Columns.Add(messageColumn);
                    dataGridView.Rows.Add("No flashcards found.");
                }
    
                // Restore column visibility state
                RestoreColumnVisibilityState();
    
                // Update the status label with the count
                statusLabel.Text = $"Total Items: {flashcards.Count}";
            }
    
            /// <summary>
            /// Populates the ContextMenuStrip with the current DataGridView columns.
            /// Ensures no duplicate menu items are added.
            /// </summary>
            private void PopulateColumnContextMenu()
            {
                columnContextMenu.Items.Clear(); // Clear existing items to prevent duplication
    
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    // Skip hidden or irrelevant columns if necessary
                    // For example, you might want to skip the "ID" column
                    if (column.Name == "ID") continue;
    
                    // Create a ToolStripMenuItem for the column
                    var menuItem = new ToolStripMenuItem(column.HeaderText)
                    {
                        Checked = column.Visible,
                        CheckOnClick = true,
                        Tag = column // Store the column in Tag for reference
                    };
                    menuItem.CheckedChanged += ColumnMenuItem_CheckedChanged;
    
                    // Add the menu item to the ContextMenuStrip
                    columnContextMenu.Items.Add(menuItem);
                }
            }
    
            /// <summary>
            /// Handles the CheckedChanged event of ContextMenuStrip items to toggle column visibility.
            /// </summary>
            private void ColumnMenuItem_CheckedChanged(object sender, EventArgs e)
            {
                if (sender is ToolStripMenuItem menuItem && menuItem.Tag is DataGridViewColumn column)
                {
                    column.Visible = menuItem.Checked;
                    columnVisibilityState[column.Name] = column.Visible; // Update the visibility state
                }
            }
    
            /// <summary>
            /// Shows the ContextMenuStrip when the user right-clicks on a column header.
            /// </summary>
            private void DataGridView_MouseUp(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Right)
                {
                    var hitTestInfo = dataGridView.HitTest(e.X, e.Y);
                    if (hitTestInfo.Type == DataGridViewHitTestType.ColumnHeader)
                    {
                        // Show the ContextMenuStrip at the mouse position
                        columnContextMenu.Show(dataGridView, new Point(e.X, e.Y));
                    }
                }
            }
    
            /// <summary>
            /// Adds a new flashcard to the Firebase database.
            /// </summary>
            private async void AddData()
            {
                var newFlashcard = CreateFlashcardFromInputs();
                if (newFlashcard != null)
                {
                    try
                    {
                        var response = await firebaseClient
                            .Child("flashcards")
                            .PostAsync(newFlashcard);
    
                        newFlashcard.id = response.Key;
                        await LoadDataAsync();
                        ClearInputs();
                        MessageBox.Show("Flashcard added successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error adding flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
    
            /// <summary>
            /// Updates the selected flashcard in the Firebase database.
            /// </summary>
            private async void UpdateData()
            {
                if (dataGridView.SelectedRows.Count > 0)
                {
                    var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem;
                    var updatedFlashcard = CreateFlashcardFromInputs();
                    if (updatedFlashcard != null)
                    {
                        updatedFlashcard.id = selectedFlashcard.id;
                        updatedFlashcard.timestamp = selectedFlashcard.timestamp; // Zaman damgasını koru
                        try
                        {
                            await firebaseClient
                                .Child("flashcards")
                                .Child(selectedFlashcard.id)
                                .PutAsync(updatedFlashcard);
    
                            await LoadDataAsync();
                            ClearInputs();
                            MessageBox.Show("Flashcard updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please select a flashcard to update.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
    
            /// <summary>
            /// Deletes selected flashcards from the Firebase database.
            /// </summary>
            private async void DeleteData()
            {
                if (dataGridView.SelectedRows.Count > 0)
                {
                    int selectedCount = dataGridView.SelectedRows.Count;
                    var confirmResult = MessageBox.Show($"Are you sure you want to delete {selectedCount} flashcard(s)?",
                                                        "Confirm Delete",
                                                        MessageBoxButtons.YesNo,
                                                        MessageBoxIcon.Question);
                    if (confirmResult == DialogResult.Yes)
                    {
                        try
                        {
                            // Create a list of delete tasks
                            var deleteTasks = dataGridView.SelectedRows
                                .Cast<DataGridViewRow>()
                                .Select(row =>
                                {
                                    var flashcard = (FlashcardItem)row.DataBoundItem;
                                    return firebaseClient.Child("flashcards").Child(flashcard.id).DeleteAsync();
                                })
                                .ToList();
    
                            // Execute all delete tasks in parallel
                            await Task.WhenAll(deleteTasks);
    
                            // Clear inputs and reload data
                            ClearInputs();
                            await LoadDataAsync();
    
                            MessageBox.Show($"{selectedCount} flashcard(s) deleted successfully!",
                                            "Success",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Error deleting flashcards: {ex.Message}",
                                            "Error",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please select one or more flashcards to delete.",
                                    "No Selection",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                }
            }
    
            /// <summary>
            /// Creates a FlashcardItem object from the input fields.
            /// </summary>
            private FlashcardItem CreateFlashcardFromInputs()
            {
                string title = txtTitle.Text == "Title" ? "" : txtTitle.Text.Trim();
                string category = txtCategory.Text == "Category" ? "Uncategorized" : txtCategory.Text.Trim();
                string content = txtContent.Text == "Content" ? "" : txtContent.Text.Trim();
                string backgroundColor = txtBackgroundColor.Text == "Background Color" ? "" : txtBackgroundColor.Text.Trim();
    
                if (string.IsNullOrEmpty(title))
                {
                    MessageBox.Show("Title cannot be empty.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }
    
                return new FlashcardItem
                {
                    title = title,
                    category = category,
                    content = content,
                    favorite = chkFavorite.Checked,
                    pinned = chkPinned.Checked,
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    backgroundColor = backgroundColor
                };
            }
    
            /// <summary>
            /// Clears the input fields and resets placeholders.
            /// </summary>
            private void ClearInputs()
            {
                txtTitle.Text = "Title";
                txtTitle.ForeColor = Color.Gray;
                txtCategory.Text = "Category";
                txtCategory.ForeColor = Color.Gray;
                txtContent.Text = "Content";
                txtContent.ForeColor = Color.Gray;
                txtBackgroundColor.Text = "Background Color";
                txtBackgroundColor.ForeColor = Color.Gray;
                chkFavorite.Checked = false;
                chkPinned.Checked = false;
            }
    
            /// <summary>
            /// Handles the selection change in the DataGridView to populate the input fields.
            /// </summary>
            private void DataGridView_SelectionChanged(object sender, EventArgs e)
            {
                if (dataGridView.SelectedRows.Count > 0)
                {
                    var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem;
                    txtTitle.Text = selectedFlashcard.title;
                    txtTitle.ForeColor = Color.Black;
                    txtCategory.Text = selectedFlashcard.category;
                    txtCategory.ForeColor = Color.Black;
                    txtContent.Text = selectedFlashcard.content;
                    txtContent.ForeColor = Color.Black;
                    txtBackgroundColor.Text = selectedFlashcard.backgroundColor;
                    txtBackgroundColor.ForeColor = Color.Black;
                    chkFavorite.Checked = selectedFlashcard.favorite;
                    chkPinned.Checked = selectedFlashcard.pinned;
                }
            }
    
            /// <summary>
            /// Sets up a real-time listener to Firebase to update data upon changes.
            /// </summary>
            private void RealTimeListener()
            {
                firebaseClient
                    .Child("flashcards")
                    .AsObservable<FlashcardItem>()
                    .Subscribe(d =>
                    {
                        Invoke((Action)(async () => await LoadDataAsync()));
                    });
            }
    
            /// <summary>
            /// Handles the Search button click to apply search criteria.
            /// </summary>
            private void SearchData()
            {
                string searchText = txtSearch.Text;
                if (string.IsNullOrWhiteSpace(searchText) || searchText == "Search...")
                {
                    currentSearchTerm = "";
                }
                else
                {
                    currentSearchTerm = searchText.ToLower();
                }
    
                ApplyFiltersAndSort();
            }
    
            /// <summary>
            /// Clears the search input and resets search filter.
            /// </summary>
            private void ClearSearch()
            {
                txtSearch.Text = "Search...";
                txtSearch.ForeColor = Color.Gray;
                currentSearchTerm = "";
                ApplyFiltersAndSort();
            }
    
            /// <summary>
            /// Formats the timestamp column to display human-readable dates.
            /// </summary>
            private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                if (dataGridView.Columns[e.ColumnIndex].Name == "timestamp")
                {
                    if (e.Value != null && long.TryParse(e.Value.ToString(), out long timestamp))
                    {
                        DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
                        DateTime dateTime = dateTimeOffset.ToOffset(TimeSpan.FromHours(3)).DateTime; // Türkiye saati için UTC+3
                        e.Value = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                        e.FormattingApplied = true;
                    }
                }
            }
    
            /// <summary>
            /// Handles the column header click event to apply sorting.
            /// </summary>
            private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
            {
                string columnName = dataGridView.Columns[e.ColumnIndex].Name;
    
                // Only allow sorting on 'title' and 'timestamp' columns
                if (columnName == "title" || columnName == "timestamp")
                {
                    // Toggle sort direction if the same column is clicked
                    if (currentSortColumn == columnName)
                    {
                        sortAscending = !sortAscending;
                    }
                    else
                    {
                        // Default to ascending if a new column is clicked
                        currentSortColumn = columnName;
                        sortAscending = true;
                    }
    
                    // Apply sorting and refresh DataGridView
                    ApplyFiltersAndSort();
    
                    // Reset sort glyphs on all columns
                    foreach (DataGridViewColumn column in dataGridView.Columns)
                    {
                        column.HeaderCell.SortGlyphDirection = SortOrder.None;
                    }
    
                    // Set sort glyph on the sorted column
                    dataGridView.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = sortAscending ? SortOrder.Ascending : SortOrder.Descending;
                }
            }
    
            /// <summary>
            /// Handles the CheckedChanged events for filtering CheckBoxes.
            /// </summary>
            private void FilterCheckBoxChanged(object sender, EventArgs e)
            {
                ApplyFiltersAndSort();
            }
    
            /// <summary>
            /// Restores the column visibility state from the stored dictionary.
            /// </summary>
            private void RestoreColumnVisibilityState()
            {
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    if (columnVisibilityState.TryGetValue(column.Name, out bool isVisible))
                    {
                        column.Visible = isVisible;
                    }
                }
            }
        }
    
        /// <summary>
        /// Represents a Flashcard item.
        /// </summary>
        public class FlashcardItem
        {
            public string id { get; set; }
            public string category { get; set; }
            public string title { get; set; }
            public string content { get; set; }
            public bool favorite { get; set; }
            public bool pinned { get; set; }
            public long timestamp { get; set; }
            public string backgroundColor { get; set; }
        }
    }
    

    Artık MenuStrip pencerenin üst kısmında, DataGridView ise menünün hemen altında yer alıyor. Kontroller arasındaki boşluklar da standart Windows Forms arayüzündeki gibi ayarlandı.

    Umarım yardımcı olabilmişimdir!