البرمجة

كيفية الحصول على DataTable من DataGridView في C#

It looks like you are trying to access the DataSource property of the DataGridView to get the underlying DataTable, but you are encountering a null value. This could be due to the way the data binding is set up.

In your code, you are filling the TestTable twice in the Form_Load event. This may not be necessary, as you are essentially filling it twice without any purpose. However, this should not cause the DataSource to be null.

The issue might be related to how the data binding is set up in your form. Make sure that you have set the data source correctly before trying to access it. Here’s a revised version of your code:

csharp
private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'testDBDataSet.TestTable' table. You can move, or remove it, as needed. this.testTableTableAdapter.Fill(this.testDBDataSet.TestTable); // Check if the DataSource is set before accessing it if (dgvTestData.DataSource != null) { DataTable dt = ((BindingSource)dgvTestData.DataSource).DataSource as DataTable; if (dt != null) { // Do something with the DataTable } } }

This revised code checks if the DataSource property of the DataGridView is not null before trying to access it. It then casts the DataSource to a BindingSource and gets the DataSource of the BindingSource as a DataTable. If the DataTable is not null, you can then proceed to work with it.

Make sure that the DataSource property of the DataGridView is set correctly in your form design or in your code before the Form_Load event is triggered. If the DataSource is not set, you will get a null value when trying to access it.

المزيد من المعلومات

في تطبيقك، يبدو أنك تحاول الوصول إلى DataTable المرتبطة بـ DataGridView بشكل غير صحيح. في الواقع، عندما تقوم بربط DataGridView بمصدر بيانات مثل DataTable، يتم إنشاء BindingSource كوسيط بينهما. وهذا يعني أنه عند الحاجة إلى الوصول إلى DataTable، يجب عليك الحصول على البيانات من BindingSource بدلاً من DataGridView مباشرة.

لذا، في حالتك، يمكنك تصحيح الكود ليكون كما يلي:

csharp
private void Form1_Load(object sender, EventArgs e) { this.testTableTableAdapter.Fill(this.testDBDataSet.TestTable); BindingSource bs = (BindingSource)dgvTestData.DataSource; DataTable dt = (DataTable)bs.DataSource; }

بهذا التعديل، يجب أن تتمكن الآن من الحصول على DataTable بشكل صحيح من BindingSource المرتبط بـ DataGridView.

زر الذهاب إلى الأعلى