locked
Need help converting from VB to C# RRS feed

  • Question

  • User-1797368610 posted

    Hi,

    i need help on below code to convert into C# from visual Basic. all i am trying to check the datatable and apply the substrings to get the daynum, mth but problem is dont know how to fit substring into below code because Mid function not work in C#. how to apply substring into below code?

    If Not IsDBNull(dr("maint_end_date")) And Len(dr("maint_end_date")) > 1 Then
    daynum = Mid(dr("maint_end_date").ToString, 1, 2)
    mth = Mid(dr("maint_end_date").ToString, 4, 3)
    If mth = "FEB" And daynum = 29 Then
    mntenddt = "'01-MAR-" & Ddl_newyears.SelectedItem.Value & "'"
    Else
    mntenddt = "'" & dr("maint_end_date").ToString.Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) & "'"
    End If
    Else
    mntenddt = "null"
    End If



    Tuesday, January 14, 2020 10:03 PM

Answers

  • User288213138 posted

    Hi Rakib1,

    if (!Information.IsDBNull(dr("maint_end_date")) & Strings.Len(dr("maint_end_date")) > 1)
                        {
                            daynum = Strings.Mid(dr("maint_end_date").ToString(), 1, 2);
                            mth = Strings.Mid(dr("maint_end_date").ToString(), 4, 3);
                            if (mth == "FEB" & daynum == 29)
                                mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                            else
                                mntenddt = "'" + dr("maint_end_date").ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                        }
                        else
                            mntenddt = "null";

    In your code, there are some VB methods, you need to replace it with C # method. such as Information.IsDBNull(), Strings.Len(), Strings.Mid(). etc.

    if (dr["maint_end_date"] != DBNull.Value & dr["maint_end_date"].ToString().Length > 1)
                    {
                        daynum = dr["maint_end_date"].ToString().Substring(1, 2);
    
                        mth = dr["maint_end_date"].ToString().Substring(4, 3);
                        if (mth == "FEB" & daynum == 29)
                            mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                        else
                            mntenddt = "'" + dr["maint_end_date"].ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                    }

    If you have any questions please let me know.

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 16, 2020 8:34 AM

All replies

  • User281315223 posted

    The Substring() method is the C# equivalent of Mid from Visual Basic, so you can use them interchangeably:

    // Visual Basic
    daynum = Mid(dr("maint_end_date").ToString, 1, 2)
    
    // C#
    daynum = dr("maint_end_date").ToString().Substring(1, 2);

    However, it looks like you are parsing dates here. If that's the case, you may want to consider using the DateTime.ParseExact() method which will allow you to define a formatting string and convert it into a DateTime object that will allow you to access things like DayOfWeek, Day, Month, Year, etc.

    You might consider sharing what your dates look like, as it might be as simple as:

    // Get your date string
    var dateString = dr["maint_end_date"].ToString();
    
    // Parse it into a date (example for something like "mon-01-2020", etc.)
    var date = DateTime.ParseExact(dateString, "ddd-MM-yyyy", null);

    Tuesday, January 14, 2020 10:29 PM
  • User-1797368610 posted

    Still getting error. could you please convert whole code into C#? i did most of the part already but getting error.

    Thanks for your help.

    DataTable ds = DatabaseConnections.GetDataTable(query);
    
                    foreach (DataRow dr in ds.Rows)
                    {
                        if (dr.Table.Columns.Contains("item_description"))
                            item_descr = "" + dr["item_description"].ToString() + "";
                        else
                            item_descr = "null";
    
                        if (dr.Table.Columns.Contains("vendor_id"))
                            vendor_id = dr["vendor_id"].ToString();
                        else
                            vendor_id = "null";
                        if (dr.Table.Columns.Contains("estimated_amount"))
                            estamt = dr["estimated_amount"].ToString();
                        else
                            estamt = "null";
                        if (dr.Table.Columns.Contains("renewal_type"))
                            renewtyp = "'" + dr["renewal_type"].ToString() + "'";
                        else
                            renewtyp = "null";
    
    
                        if (dr.Table.Columns.Contains("maint_end_date"))
                        {   
                            daynum =  dr("maint_end_date").ToString.Substring(0, 2);
                            mth = dr("maint_end_date").ToString.Substring(3, 3);
    
                            if
                                     (mth = "FEB" && daynum = 29)
                                mntenddt = "\'01-MAR-" + (ddlNewYear.SelectedItem.Value + "\'");
    
                            else
    
                                mntenddt = ("\'" + (dr["maint_end_date"].ToString().Replace(ddlOldYear.SelectedItem.Value, ddlNewYear.SelectedItem.Value) + "\'"));
    
    
                        }
                        else
                            mntenddt = "null";

    Tuesday, January 14, 2020 10:51 PM
  • User409696431 posted

    Since your code is incomplete (for example you haven't defined item_descr or vendor_id, and so on, anywhere in the code you show, although you have assigned values to them), it would be more useful if you told us what errors you were getting, on which line.  Or show us all the code, including where everything is defined.

    Wednesday, January 15, 2020 12:27 AM
  • User288213138 posted

    Hi Rakib1,

    Rakib1

    Still getting error. could you please convert whole code into C#? i did most of the part already but getting error.

    Since your code is incomplete, I am not sure where your errors are.

    But if you want to convert VB into C# code. you can use this tool: http://converter.telerik.com/

    If you still have questions, please post your complete code.

    Best regards,

    Sam

    Wednesday, January 15, 2020 2:16 AM
  • User-1797368610 posted

    Thanks for your reply. Below is the convert code from VB to C#. if you notice in the code with color having issue. may be just we need tweak here few attributes. any question please let me know.

    using System;
    using System.Web.UI;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Data;
    using System.Web.UI.WebControls;
    using System.Collections;
    
    public partial class CopyData : System.Web.UI.Page
    {
        private int reccount;
    
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string query;
            if (!IsPostBack)
            {
                query = "select max(to_char(maint_end_date,'yyyy')) maxyr from  T_HDC_MAINTENANCE_SCHEDULE3 ";
                query = query + " where maint_end_date is not null ";
                PopulateOldYearDropdownList();
                PopulateNewYearDropdownList();
    
            }
        }
        protected void PopulateOldYearDropdownList()
        {
            MaintenanceOldYearDropDownList OldYear = new MaintenanceOldYearDropDownList(
                ddlOldYear,
                "select distinct to_char(maint_end_date, 'yyyy') years from  T_HDC_MAINTENANCE_SCHEDULE3 where maint_end_date is not null order by years ",
                "years",
                "years");
            OldYear.PopulateDropDownList();
            OldYear.InsertItemIntoDropDownList("", "0", 0);
        }
        public void PopulateNewYearDropdownList()
        {
            int yearval = 2019;
            ArrayList YearValues = new ArrayList();
    
            for (var i = 0; i <= 10; i++)
            {
                yearval = yearval + 1;
                YearValues.Add(yearval);
            }
    
            // assign year values to the drop down list of year
            ddlNewYear.Items.Clear();
            ddlNewYear.DataSource = YearValues;
            ddlNewYear.DataBind();
        }   
    
        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("Home.aspx");
        }
    
        protected void btnCopy_Click(object sender, EventArgs e)
        {
            string alert, query, dowk, mth, oldmntdt;
            bool fnd = false;
            int reccount, daynum, yr, lpyr;
            // DataSet ds;
            string item_descr, vendor_id, estamt, renewtyp, mntenddt, actamt, ponum, contact, stat, stat_dt;
            string create_dt, update_dt, contact_email;
            //Lblexception.Text = " ";
            try
            {
    
                // check if records already exist for new year
                query = "select count(to_char(maint_end_date,'yyyy')) cnt" + " from  T_HDC_MAINTENANCE_SCHEDULE3 " + " where maint_end_date is not null " + " and to_char(maint_end_date,'yyyy') = " + ddlNewYear.SelectedItem.Text;
                reccount = ExecuteScalarCommand(query);
    
                if (reccount > 0)
                {
                    alert = "<script language='javascript'>" + "alert ('Records already exist for this calendar year. Select another value for the new year'); " + "</script>";
                    ClientScript.RegisterStartupScript(typeof(Page), "ClientScript", alert);
                }
                else
                {
                    // retieve records for the selected year
                    query = "select item_description, vendor_id, estimated_amount, renewal_type,  " + " to_char(maint_end_date,'dd-MON-YYYY') maint_end_date, actual_amount, po_number, contact_person, " + " status, to_char(status_date,'dd-MON-YYYY') status_date, contact_email, " + " to_char(creation_date,'dd-MON-YYYY') creation_date, " + " to_char(last_update_date,'dd-MON-YYYY') last_update_date " + " from T_HDC_MAINTENANCE_SCHEDULE3 " + " where maint_end_date is not null " + " and to_char(maint_end_date,'yyyy') = " + ddlOldYear.SelectedItem.Text;               
    
                    DataTable ds = DatabaseConnections.GetDataTable(query);
    
                    foreach (DataRow dr in ds.Rows)
                    {
                        if (dr.Table.Columns.Contains("item_description"))
                            item_descr = "" + dr["item_description"].ToString() + "";
                        else
                            item_descr = "null";
    
                        if (dr.Table.Columns.Contains("vendor_id"))
                            vendor_id = dr["vendor_id"].ToString();
                        else
                            vendor_id = "null";
                        if (dr.Table.Columns.Contains("estimated_amount"))
                            estamt = dr["estimated_amount"].ToString();
                        else
                            estamt = "null";
                        if (dr.Table.Columns.Contains("renewal_type"))
                            renewtyp = "'" + dr["renewal_type"].ToString() + "'";
                        else
                            renewtyp = "null";
    
                        if (!Information.IsDBNull(dr("maint_end_date")) & Strings.Len(dr("maint_end_date")) > 1)
                        {
                            daynum = Strings.Mid(dr("maint_end_date").ToString(), 1, 2);
                            mth = Strings.Mid(dr("maint_end_date").ToString(), 4, 3);
                            if (mth == "FEB" & daynum == 29)
                                mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                            else
                                mntenddt = "'" + dr("maint_end_date").ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                        }
                        else
                            mntenddt = "null";
                       
                        if (dr.Table.Columns.Contains("actual_amount"))
                            actamt = dr["actual_amount"].ToString();
                        else
                            actamt = "null";
                        if (dr.Table.Columns.Contains("po_number"))
                            ponum = dr["po_number"].ToString();
                        else
                            ponum = "null";
                        if (dr.Table.Columns.Contains("contact_person"))
                            contact = "'" + dr["contact_person"].ToString() + "'";
                        else
                            contact = "null";
                        if (dr.Table.Columns.Contains("contact_email"))
                            contact_email = "'" + dr["contact_email"].ToString() + "'";
                        else
                            contact_email = "null";
                        if (dr.Table.Columns.Contains("status"))
                            stat = "'" + dr["status"].ToString() + "'";
                        else
                            stat = "null";
                        if (dr.Table.Columns.Contains("status_date"))
                            stat_dt = "'" + dr["status_date"].ToString() + "'";
                        else
                            stat_dt = "null";
                        if (dr.Table.Columns.Contains("creation_date"))
                            create_dt = "'" + dr["creation_date"].ToString() + "'";
                        else
                            create_dt = "null";
                        if (dr.Table.Columns.Contains("last_update_date"))
                            update_dt = "'" + dr["last_update_date"].ToString() + "'";
                        else
                            update_dt = "null";
                        query = "insert into t_hdc_maintenance_schedule3 (item_description, vendor_id, estimated_amount, renewal_type,";
                        query = query + "maint_end_date, actual_amount, po_number, contact_person, contact_email,";
                        query = query + "status, status_date,last_update_date,creation_date)";
                        query = query + " VALUES ( '" + item_descr + "'," + vendor_id + "," + estamt + "," + renewtyp;
                        query = query + "," + mntenddt + "," + actamt + ",null," + contact + "," + contact_email;
                        query = query + ",null,null,sysdate,sysdate)";
    
                        DatabaseConnections.ExecuteScalarCommand(query);
                    }
    
                    // retrieve newly inserted records
                    query = "select to_char(maint_end_date, 'dd-MON-yyyy' ) maint_end_date,to_char(maint_end_date, 'DY-yyyy' ) daystr, " + " to_char(maint_end_date, 'dd-mm-yyyy' ) dayval " + " from T_HDC_MAINTENANCE_SCHEDULE3 " + " where maint_end_date is not null " + " and to_char(maint_end_date,'yyyy') = " + ddlNewYear.SelectedItem.Value;
                    DatabaseConnections.ExecuteScalarCommand(query);
    
                    foreach (DataRow dr in ds.Rows)
                    {
                        if (!Information.IsDBNull(dr("maint_end_date")))
                        {
                            daynum = Strings.Mid(dr("maint_end_date").ToString(), 1, 2);
                            mth = Strings.Mid(dr("maint_end_date").ToString(), 4, 3);
                            yr = Strings.Mid(dr("maint_end_date").ToString(), 8);
                            oldmntdt = "'" + dr("maint_end_date") + "'";
                        }
                        if (!Information.IsDBNull(dr("daystr")))
                            dowk = Strings.Mid(dr("daystr").ToString(), 1, 3);
                        if (dowk == "SAT")
                            daynum = daynum + 2;
                        if (dowk == "SUN")
                            daynum = daynum + 1;
                        // adjust day number if more than 30 days
                        if ((mth == "APR" | mth == "JUN" | mth == "SEP" | mth == "NOV") & daynum > 30)
                        {
                            daynum = daynum - 30;
                            if (mth == "APR")
                                mth = "MAY";
                            if (mth == "JUN")
                                mth = "JUL";
                            if (mth == "SEP")
                                mth = "OCT";
                            if (mth == "NOV")
                                mth = "DEC";
                        }
                        else if (daynum > 31)
                        {
                            daynum = daynum - 31;
                            switch (mth)
                            {
                                case "JAN":
                                    {
                                        mth = "FEB";
                                        break;
                                    }
    
                                case "MAR":
                                    {
                                        mth = "APR";
                                        break;
                                    }
    
                                case "MAY":
                                    {
                                        mth = "JUN";
                                        break;
                                    }
    
                                case "JUL":
                                    {
                                        mth = "AUG";
                                        break;
                                    }
    
                                case "AUG":
                                    {
                                        mth = "SEP";
                                        break;
                                    }
    
                                case "OCT":
                                    {
                                        mth = "NOV";
                                        break;
                                    }
    
                                case "DEC":
                                    {
                                        mth = "JAN";
                                        yr = yr + 1;
                                        break;
                                    }
    
                                default:
                                    {
                                        break;
                                    }
                            }
                        }
                        lpyr = yr % 4;
                        // adjust day number for Feb
                        if (mth == "FEB" & daynum > 28)
                        {
                            daynum = daynum - 28;
                            mth = "MAR";
                        }
                        mntenddt = daynum.ToString() + "-" + mth + "-" + yr.ToString();
                        query = "update T_HDC_MAINTENANCE_SCHEDULE3 set maint_end_date = '" + mntenddt + "' where maint_end_date = " + oldmntdt;
    
                        DatabaseConnections.ExecuteScalarCommand(query);
                    }
    
                    if (ds == null)
                    {
                    }
                }
                //Lblexception.Text = "* Records were copied successfully.";
            }
            catch (Exception ex)
            {
            }
        }
    
        private int ExecuteScalarCommand(string query)
        {
            DatabaseConnections.ExecuteScalarCommand(query);
            return reccount;
        }
    }
    
    

    Wednesday, January 15, 2020 3:42 PM
  • User409696431 posted

    "if you notice in the code with color having issue"

    What issues?  In Visual Studio, if there is a problem with code that can be determined before running it, VS will underline the problem areas with a squggly red line.  Hover your mouse over the underlined item and it will tell you the error.

    What errors are you getting?

    If we put your code in VS, we'll get errors simply because we don't have your .aspx page, and references to controls on the page, such as MaintenanceOldYearDropDownList, will not be understood.

    Trying to ignore errors that are likely controls on your page, I also get errors for DatabaseConnections, Information, and Strings (which are not defined anywhere in the .cs or .aspx file).  Also, GetDataTable(query) is not defined anywhere.

    For the case of Strings, the problem is that you are using Strings.Mid which is VB, not C#.  Rion's first post showed you how to use C#'s substring method instead.

    There are also several places where you are doing a compare with a variable that has been defined as a string (good), but not initialized before the comparison (bad: you can't compare something to nothing).  Either initialize them with a default value, or only do the comparison inside an "if" statement that sucessfully found a value for them, not in both cases where they may have a value and may not have a value.

    Two examples:

    if ((mth == "APR" | mth == "JUN" | mth == "SEP" | mth == "NOV") & daynum > 30)
                        {
                            daynum = daynum - 30;
                            if (mth == "APR")
                                mth = "MAY";
                            if (mth == "JUN")
                                mth = "JUL";
                            if (mth == "SEP")
                                mth = "OCT";
                            if (mth == "NOV")
                                mth = "DEC";
                        }

    You don't always assign a value to mth, so you could be comparing nothing.  The assignment of mth shows three problems:

     if (!Information.IsDBNull(dr("maint_end_date")) & Strings.Len(dr("maint_end_date")) > 1)
                        {
                            daynum = Strings.Mid(dr("maint_end_date").ToString(), 1, 2);
                            mth = Strings.Mid(dr("maint_end_date").ToString(), 4, 3);
                            if (mth == "FEB" & daynum == 29)
                                mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                            else
                                mntenddt = "'" + dr("maint_end_date").ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                        }
                        else
                            mntenddt = "null";

    The "else" doesn't assign anything to mth, so it is possible for it to not have a value.  That causes the problem in the first section.  When mth is assigned, it is based on  the undefined "Information" and the VB Strings.Mid, so it won't work anyway.

    In the code you copied from, where do they define DatabaseConnections, GetDataTable(query), and Information?

    Wednesday, January 15, 2020 8:40 PM
  • User288213138 posted

    Hi Rakib1,

    if (!Information.IsDBNull(dr("maint_end_date")) & Strings.Len(dr("maint_end_date")) > 1)
                        {
                            daynum = Strings.Mid(dr("maint_end_date").ToString(), 1, 2);
                            mth = Strings.Mid(dr("maint_end_date").ToString(), 4, 3);
                            if (mth == "FEB" & daynum == 29)
                                mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                            else
                                mntenddt = "'" + dr("maint_end_date").ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                        }
                        else
                            mntenddt = "null";

    In your code, there are some VB methods, you need to replace it with C # method. such as Information.IsDBNull(), Strings.Len(), Strings.Mid(). etc.

    if (dr["maint_end_date"] != DBNull.Value & dr["maint_end_date"].ToString().Length > 1)
                    {
                        daynum = dr["maint_end_date"].ToString().Substring(1, 2);
    
                        mth = dr["maint_end_date"].ToString().Substring(4, 3);
                        if (mth == "FEB" & daynum == 29)
                            mntenddt = "'01-MAR-" + Ddl_newyears.SelectedItem.Value + "'";
                        else
                            mntenddt = "'" + dr["maint_end_date"].ToString().Replace(Ddl_oldyears.SelectedItem.Value, Ddl_newyears.SelectedItem.Value) + "'";
                    }

    If you have any questions please let me know.

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 16, 2020 8:34 AM
  • User-1797368610 posted

    Thanks for your help Samwu. it helps to resolve my problem.

    Thursday, January 16, 2020 4:00 PM