Hi @sanchita goel , Welcome to Microsoft Q&A,
Your problem lies in the conversion use of BindingSource and BindingList.
Refer to their official documentationBindingSource 和 BindingList.
using System.ComponentModel;
using System.Windows.Forms;
namespace xxx
{
public partial class Form1 : Form
{
private BindingList<StockItem> stockItems;
private BindingSource bindingSource1;
public Form1()
{
InitializeComponent();
InitializeData();
}
private void InitializeData()
{
// Create the BindingList to hold stock items
stockItems = new BindingList<StockItem>();
// Set the DataSource of the BindingSource to the BindingList
bindingSource1 = new BindingSource { DataSource = stockItems };
// Assign the BindingSource as the DataSource for both DataGridViews
dataGridView1.DataSource = bindingSource1;
dataGridView2.DataSource = bindingSource1;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string enteredText = textBox1.Text;
// Create a new stock item with the entered text and quantity 0
StockItem newItem = new StockItem(enteredText, 0);
// Add the new stock item to the BindingList
stockItems.Add(newItem);
// Clear the TextBox after adding the item
textBox1.Clear();
}
}
}
public class StockItem
{
public string Name { get; set; }
public int Quantity { get; set; }
public StockItem(string name, int quantity)
{
Name = name;
Quantity = quantity;
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.