Send value from one Windows Form to another using Property class in C# and VB.Net

Last Reply 7 months ago By pandeyism

Posted 7 months ago

hi sir,

i am getting error "object reference not set to an instance of an object in c#" in c#.

when accessing combobox,it will show an error.The value of combo box is not passed to parameter

fisrt form code

public partial class SelectStudents : Form
  { private void studentsNoCB_SelectedIndexChanged(object sender, EventArgs e)
      {           
         comboboxvalue .StudNo = this.studentsNoCB.Text.ToString () ;           
      }
  }
  public static class comboboxvalue
  {
      public static string StudNo;
      public static string  getstudentNo()
      {           
          return StudNo;
      }
  }

second form code

        private void FeesofMonthCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(rollNO);
            try
            {
                conn1.ConnectionString = "server=localhost;user id=root;password=;database=studentfeescollection;Convert Zero Datetime=True";
                conn1.Open();
                Sql = "SELECT COUNT(AdmissionNo) as COUNT FROM tblfeescollection WHERE AdmissionNo=@p1 AND FeesMonth=@p2;";
                cmd = new MySqlCommand(Sql, conn1);
                cmd.Parameters.AddWithValue("@p1", rollNO);
                cmd.Parameters.AddWithValue("@p2", FeesofMonthCB.SelectedItem);               
                dr1 = cmd.ExecuteReader();
                while (dr1.Read())
                {                   
                        if (dr1.GetString("COUNT")!= null)
                    {
                        string count1 = dr1.GetString("COUNT");
                        count = Convert.ToInt32(count1);
                    }
                }
                dr1.Close();
                cmd.Dispose();
                conn1.Close();
                conn2.ConnectionString = "server=localhost;user id=root;password=;database=studentfeescollection;Convert Zero Datetime=True";
                conn2.Open();
                Sql = "SELECT RemBal FROM tblfeescollection WHERE AdmissionNo=@p1 ORDER BY ID DESC LIMIT 1 ";
                cmd = new MySqlCommand(Sql, conn2);
                cmd.Parameters.AddWithValue("@p1", rollNO);
                dr2 = cmd.ExecuteReader();
                while (dr2.Read())
                {
                    if (dr1.GetString("RemBal") != null)
                        arrear = Convert.ToInt32(dr2.GetString("RemBal"));
                }
                dr2.Close();
                cmd.Dispose();
                conn2.Close();
                if (count == 0)
                {
                    try
                    {
                        conn3.ConnectionString = "server=localhost;user id=root;password=;database=studentfeescollection;Convert Zero Datetime=True";
                        conn3.Open();
                        Sql = "SELECT a.AdmissionNo,a.Name,a.PhoneNo,(b.AdmissionFees + b.TutionFees + b.MonthlyFees + b.LibraryFees + b.ExamFees + b.SportsFees) as TotalFees FROM tblstudents a JOIN tblfeesgenerate b ON a.AdmissionNo = b.AdmissionNo WHERE a.AdmissionNo = @p1; ";
                        cmd = new MySqlCommand(Sql, conn3);
                        cmd.Parameters.AddWithValue("@p1", rollNO);
                        dr3 = cmd.ExecuteReader();
                         while (dr3.Read())
                            {                           
                                regCodeTB.Text = dr3.GetString("AdmissionNo");
                                NameTB.Text = dr3.GetString("Name");
                                PhoneTB.Text = dr3.GetString("PhoneNo");
                                receivableamtTB.Text = dr3.GetString("TotalFees");
                                discountamtTB.Text = "0";
                                arrearamtTB.Text = arrear.ToString();
                                netbalanceamtTB.Text = dr3.GetString("TotalFees") + arrear;
                                paidamtTB.Text = "0";
                            }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        dr3.Close();
                        cmd.Dispose();
                        conn3.Dispose();
                    }
                }
                else if (count > 0)
                {
                    try
                    {
                        conn3.ConnectionString = "server=localhost;user id=root;password=;database=studentfeescollection;Convert Zero Datetime=True";
                        conn3.Open();
                        Sql = "SELECT a.AdmissionNo,a.Name,a.PhoneNo,b.Receivable,b.Discount,b.Arrears,b.NetBal,b.Paid,b.RemBal FROM tblstudents a JOIN tblfeescollection b ON a.AdmissionNo=b.AdmissionNo WHERE a.AdmissionNo=@p1 AND b.FeesMonth=@p2 ORDER BY b.ID DESC LIMIT 1";
                        cmd = new MySqlCommand(Sql, conn3);
                        cmd.Parameters.AddWithValue("@p1", rollNO);
                        cmd.Parameters.AddWithValue("@p2", FeesofMonthCB.SelectedItem);
                        dr3 = cmd.ExecuteReader();
                        if (dr3.HasRows)
                        {
                            while (dr3.Read())
                            {
                                regCodeTB.Text = dr3.GetString("AdmissionNo");
                                NameTB.Text = dr3.GetString("Name");
                                PhoneTB.Text = dr3.GetString("PhoneNo");
                                receivableamtTB.Text = dr3.GetString("TotalFees");
                                discountamtTB.Text = "0";
                                arrearamtTB.Text = dr3.GetString("RemBal");
                                netbalanceamtTB.Text = dr3.GetString("RemBal");
                                paidamtTB.Text = "0";
                            }
                        }                      
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        dr3.Close();
                        cmd.Dispose();
                        conn3.Dispose ();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

 

Posted 7 months ago Modified on 7 months ago

Hi PSowmiya,

Please refer below code is working-

Namespaces

C#

using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient
Imports VB.Form1

Code

C#

Form1.cs

public String Sql;
public SqlCommand cmd = new SqlCommand();
public SqlConnection conn = new SqlConnection();
public SqlDataReader dr;
public Form1()
{
    InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();
    f2.Show();
}
private void SelectStudents_Load(object sender, EventArgs e)
{
    retrieveStudentsName();
}
public void retrieveStudentsName()
{
    try
    {
        conn.ConnectionString = @"Server=.\SQL2005;DataBase=Test;UID=;PWD=";
        conn.Open();
        Sql = "SELECT * FROM Customers;";
        cmd = new SqlCommand(Sql, conn);
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            comboBox1.Items.Add(dr["CustomerId"]);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        cmd.Dispose();
        dr.Close();
        conn.Dispose();
    }
}
private void studentsNoCB_SelectedIndexChanged(object sender, EventArgs e)
{
    comboboxvalue.StudNo = this.comboBox1.Text.ToString();
}
public static class comboboxvalue
{
    public static string StudNo;
    public static string getstudentNo()
    {
        return StudNo;
    }
}

Form2.cs

string rollNO = Form1.comboboxvalue.StudNo;
public Form2()
{
    InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{
    string constr = @"Server=.\SQL2005;DataBase=Test;UID=;PWD="; ;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE CustomerId=@CustomerId", con))
        {
            cmd.Parameters.AddWithValue("@CustomerId", rollNO);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                this.dataGridView1.DataSource = dt;
            }
        }
    }
}

VB.Net

Form1.vb

Public Sql As String
Public cmd As SqlCommand = New SqlCommand()
Public conn As SqlConnection = New SqlConnection()
Public dr As SqlDataReader
Public Sub New()
    InitializeComponent()
End Sub

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click
    Dim f2 As Form2 = New Form2()
    f2.Show()
End Sub

Private Sub SelectStudents_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    retrieveStudentsName()
End Sub

Public Sub retrieveStudentsName()
    Try
        conn.ConnectionString = "Server=.\SQL2005;DataBase=Test;UID=;PWD="
        conn.Open()
        Sql = "SELECT * FROM Customers;"
        cmd = New SqlCommand(Sql, conn)
        dr = cmd.ExecuteReader()

        While dr.Read()
            comboBox1.Items.Add(dr("CustomerId"))
        End While

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        cmd.Dispose()
        dr.Close()
        conn.Dispose()
    End Try
End Sub

Private Sub studentsNoCB_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles comboBox1.SelectedIndexChanged
    comboboxvalue.StudNo = Me.comboBox1.Text.ToString()
End Sub

Class comboboxvalue
    Public Shared StudNo As String
    Function getstudentNo() As String
        Return StudNo
    End Function
End Class

Form2.vb

Private rollNO As String = comboboxvalue.StudNo
Public Sub New()
    InitializeComponent()
End Sub

Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim constr As String = "Server=.\SQL2005;DataBase=Test;UID=;PWD="
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers WHERE CustomerId=@CustomerId", con)
            cmd.Parameters.AddWithValue("@CustomerId", rollNO)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                da.Fill(dt)
                Me.dataGridView1.DataSource = dt
            End Using
        End Using
    End Using
End Sub

Screenshot