البرمجة

تجنب NullReferenceException في قراءة أسماء الجداول من قاعدة البيانات في C#

The error “Object reference not set to an instance of an object” typically occurs when you try to access a member of a null object reference. In your case, it’s likely that Reader2["name"] is null for some rows, causing the ToString() method to throw an exception. To fix this, you can check if the value is null before trying to access it. Here’s how you can modify your code:

csharp
while (Reader2.Read()) { if (!Reader2.IsDBNull(Reader2.GetOrdinal("name"))) { cmbAlterAdd1.Items.Add(Reader2["name"].ToString()); } }

This modification checks if the “name” column value is not null before adding it to the cmbAlterAdd1 combo box.

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

بالطبع! الخطأ “Object reference not set to an instance of an object” يحدث عندما تحاول الوصول إلى عضو في مرجع كائن فارغ (null). في حالتك، من المحتمل أن Reader2["name"] يكون فارغًا (null) لبعض الصفوف، مما يتسبب في رمي استثناء من طرف الدالة ToString().

لحل هذه المشكلة، يمكنك التحقق مما إذا كانت القيمة فارغة قبل محاولة الوصول إليها. هنا كيف يمكنك تعديل الكود الخاص بك:

csharp
while (Reader2.Read()) { if (!Reader2.IsDBNull(Reader2.GetOrdinal("name"))) { cmbAlterAdd1.Items.Add(Reader2["name"].ToString()); } }

هذا التعديل يتحقق مما إذا كانت قيمة العمود “name” ليست فارغة قبل إضافتها إلى cmbAlterAdd1.

شاهد أيضاً
إغلاق
زر الذهاب إلى الأعلى