Windows Form Error: Value of Type label cannot be converted to Control in VB.Net

Last Reply one month ago By PSowmiya

Posted one month ago

Hi Sir

I am creating labels dynamically and these labels to the tabpage. My code is: 

  Dim sKeyText As Label = New Label()
  Dim sKeyValue As Label = New Label()
  sKeyText.AutoSize = True
  sKeyText.Location = New Point(67, 610)
  sKeyText.Text = "Server License Key:"
  sKeyValue.AutoSize = True
  sKeyValue.Location = New Point(196, 610)
  sKeyValue.Text = dr.GetString("ServerLicencse")
  licenseInfoTP.Controls.Add(sKeyText)
  LicenseInfoTP.Controls.Add(sKeyValue)

It gives me error.The error is Value of Type 'label' cannot be converted to 'Control'.

Please help me...

Posted one month ago Modified on one month ago

Hi PSowmiya,

Refer below sample.

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    string constr = @"Server=\SQL2005;DataBase=Test;UID=;PWD=";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con);
    con.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    int i = 0;
    while (dr.Read())
    {
        Label sKeyText = new Label();
        sKeyText.Location = new Point(10, (25 * i) + 2);
        sKeyText.Size = new Size(150, 20);
        sKeyText.Name = "ServerLicenseKey:" + (i);
        sKeyText.Text = "ServerLicenseKey: " + (i);

        Label sKeyValue = new Label();
        sKeyValue.Location = new Point(10, (25 * i) + 2);
        sKeyValue.Size = new Size(150, 20);
        sKeyValue.Name = "DLIndia5655:" + (i);
        sKeyValue.Text = "DLIndia5655: " + (i);
        tabPage2.Controls.Add(sKeyValue);
        tabPage1.Controls.Add(sKeyText);
        i = i + 1;
    }
    con.Close();
}

VB.Net

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    Dim constr As String = "Server=\SQL2005;DataBase=Test;UID=;PWD="
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", con)
    con.Open()
    Dim dr As SqlDataReader = cmd.ExecuteReader()
    Dim i As Integer = 0

    While dr.Read()
        Dim sKeyText As Label = New Label()
        sKeyText.Location = New Point(10, (25 * i) + 2)
        sKeyText.Size = New Size(100, 20)
        sKeyText.Name = "ServerLicenseKey:" & (i)
        sKeyText.Text = "ServerLicenseKey: " & (i)
        Dim sKeyValue As Label = New Label()
        sKeyValue.Location = New Point(10, (25 * i) + 2)
        sKeyValue.Size = New Size(100, 20)
        sKeyValue.Name = "DLIndia5655:" & (i)
        sKeyValue.Text = "DLIndia5655: " & (i)
        tabPage2.Controls.Add(sKeyValue)
        tabPage1.Controls.Add(sKeyText)
        i = i + 1
    End While

    con.Close()
End Sub

Screenshot

 


Posted one month ago Modified on one month ago

Hi sir,

I added your code but the error still remains. After that I added Imports System.Windows.Forms

Now Error is gone. thank you sir.