Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Getting my F12 keypress to break out from loop.

$
0
0

Hello to you all.

Im a newbie at C# and coding in general. But i have learned some but now im stuck and need some advice from YOU guys.

I want my little console app to break out from the loop when i press F12 key.

Its from Case 1:

I bet its its a silly thing but i really need help..

(Comments in swedish cause thats my main langauge if u wonder)

cheers.

Look code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rygga
{
    class Program
    {
        static void Main(string[] args)
        {

            bool isRunning = true; // loopar
            string[] minArray = new string[4]; // Array strängen

            List<string> saKer = new List<string> { }; // List string
            while (isRunning)

            {
                    // Skapar meny´n

                    Console.WriteLine("\n************************************");
                Console.WriteLine("   Välkommen till ryggan! ");
                Console.WriteLine(" Var god och gör ert val i menyn" + "\n");
                Console.WriteLine(" [1] Lägg till föremål i stora facket");
                Console.WriteLine(" [2] Lägg till föremål i ytterfacket");
                Console.WriteLine(" [3] Lista föremål i ytterfacket");
                Console.WriteLine(" [4] Lista föremålen i stora facket");
                Console.WriteLine(" [5] Avsluta programmet.");
                Console.WriteLine("\n************************************");
                Console.Write("\nVar god och välj:  ");
                try // blir det något fel hoppar vi till rad 141 och skriver ut meddelandet från rad 144
                {
                    int menyVal = Convert.ToInt32(Console.ReadLine());  // Vad väljer användaren i menyn
                    if (menyVal == 5) break; // Avslutar programmet vid val 3

                    {
                        switch (menyVal)

                        {

                            case 1:

                                Console.Clear(); // detta kommando rensar terminalfönstret för lite "renare" utseende

                                Console.WriteLine("Vad vill du lägga i ryggan? ( Tryck på F12 för att avsluta inmatningen ) \n");

                                do {
                                    while (! Console.KeyAvailable)
                                    {
                                        saKer.Add(Console.ReadLine());
                                    }
                                } while (Console.ReadKey(true).Key != ConsoleKey.F12);

                                        break;


                            case 2:
                                Console.Clear();
                                Console.Write("Lägg till 4 saker nu :");
                                // Ytterfacket = arrayen

                                // Själva array listan
                                minArray[0] = Console.ReadLine();
                                minArray[1] = Console.ReadLine();
                                minArray[2] = Console.ReadLine();
                                minArray[3] = Console.ReadLine();

                                break;

                            case 3:
                                foreach (string stuff in minArray)
                                Console.WriteLine(" Ytterfacket innehåller följande :" + " {0}", stuff); // Listar vad arrayen innehåller

                                break;

                            case 4:
                                foreach (string item in saKer)
                                    Console.WriteLine(item); // Listar vad listan innehåller.
                                break;

                            case 5:

                                break;  // Stänger ner programmet


                        }


                    }
                }
                catch // try/catch för meddelande vid felaktig input
                {
                    Console.Clear();
                    Console.WriteLine("\n\n\n\n\n\n\t\tVar god och använd siffror i dina val! :)"); // påminer användaren om sifferval i progammet
                }



            }
        }
    }
}


Display image in pdf

$
0
0

hi

i want to display company logo in print pdf format.

i am working on windows form application using c#.net and i want to display logo image using html image tag.

please see may below code:

 <img src=\"C:\C# Projects\Fahinds\Fahinds\images\honda.jpg\" height=\"95\" width=\"120\">

using above code i am not able to get logo on pdf file.

my image is located in my project local drive.

please help to resolve my this issue ASAP.


Sort a list in C#

$
0
0

Hi,

I have asp.net with C#.net application, In this application , have a list of one class,, want to sort the alphanumeric value.Now display the salary is BP1-100000,BP2-1260,BP1-13000,BP1-160,BP2-100.But I want to display the result as,

BP1-160,BP1-1260,BP1-13000,BP1-100000,BP2-100.How can I achive?

My code is below and not achieving with this,

                 

List<Employee> empList = new List<Employee>()
  {         new Employee { Name = "BP1", Salary = "BP1-13000" } ,                   
                    new Employee { Name = "BP1", Salary = "BP1-160" } ,
                    new Employee { Name = "BP2", Salary = "BP2-1260" } ,
                      new Employee { Name = "BP1", Salary = "BP1-100000" } ,

                      new Employee { Name = "BP1", Salary = "BP2-100" }                 };

        Employee_SortBySalaryByAscendingOrder eAsc =
                new Employee_SortBySalaryByAscendingOrder();
        empList.Sort(eAsc);

  }

I have write one class or sort also, but it is not working,

class Employee_SortBySalaryByAscendingOrder : IComparer<Employee>
{
    #region IComparer<Employee> Members

    public int Compare(Employee x, Employee y)
    {
      
        return string.Compare(x.Salary, y.Salary);
    }

    #endregion
}

Guide me in Right way to get 70483 Certification.

$
0
0

Hi,

I am a 3 year experienced programmer in visual studio (C#, ASP.net, Library and both window and web Service), but i dont have any certification regarding my work. I would like to get a Certificates. While I discussed about it with my seniors, they said that the pattern is changed in a link. https://www.microsoft.com/en-us/learning/course.aspx?cid=20483 . Please help me how to get a new C# certification. 

Error code: 0xe0434f4d

$
0
0

Hey,

I am using .net Framework 3.0 at home, and my program works successfully, no problems to launch.

However at my school where they are using .net Framework 2.0 it fails to launch

Here is a screenshot:

Here is my Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace FilmScript
{
    static class Program
    {
        public static Form1 form = null;
        public static newProject newProj = null;

        public static String ProjectTitle = String.Empty;
        public static String ProjectAlreadyLoaded = "NO";
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            form = new Form1();
            newProj = new newProject();
            Application.Run(form);
        }
    }
}

I do not know why this is happening, as I have no code that could trigger a system exception, I use System.IO and XML read and saving, but do not know if that is also causing the error.

If you believe this might be the cause I will be happen to share that code with you.

Many Thanks

Andrew Swallow

Set Button backcolor to Transparent

$
0
0

Hi, 

I have to modify a Work Item control buttons and text field so the background colors of those elements (buttons, textfield, textbox) automatically change as the Visual Studio theme is modified. For that i wanted to set the button background to ''Transparent''

I tried adding the following line in the control constructor: 

         SetStyle(ControlStyles.SupportsTransparentBackColor, true);
         SetStyle(ControlStyles.Opaque, true);

I set the useVisualStypeBackColor property of the button to true and then false. FlatStype portety  to standard and then system

Unfortunately wathever option a try to play with. the button background color is still always Grey. 

Any help wull be greatly appreciated. 

PS: I'm using visual studio 2013. 

LoadLibrary("kl2dll32.dll") returning 0

$
0
0
Hello,

I'm developing a C# application in Visual Studio 2013 on Windows 10. The following line of code returns 0:

keylok = LoadLibrary("kl2dll32.dll");

LoadLibrary is a native win32 method. See this article: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx

I'm wondering why it's returning 0. I did a search for kl2dll32.dll on my machine and it turned up nothing. I'm wondering if kl2dll32.dll exists on Windows 10.

I never had this problem before when I was developing on Windows 7 or 8, only on Windows 10.

Alternatively, I could set the platform target to run in x64 mode (which matches the processor of my machine), and in that case, the application will call this:

keylok = LoadLibrary("kl2dll64.dll");

But the same thing happens here: it returns 0, and a search for kl2dll64.dll turns up nothing.

So I suspect kl2dll64.dll doesn't exist on Windows 10 either.

Have these files been replaced by something else on Windows 10?

serialization fails - how to find the culprit

$
0
0

I have a very complex application with lots of objects that reference each other. I want
to serialize one particular object - objectA. However the object refers to lots
of other objects which refer to others still - some of it circular. e.g.
objectA has a reference to objectB which has a reference to objectC which
refers objectA etc…

The serialization fails because it says that a particular objectZ is “not marked as
serializable”.

The way the application is supposed to work – objectZ is not supposed to be referenced by
objectA – even indirectly. But somehow it does. How can I find the path which
leads from objectA to objectZ?




C# Console Ifs/Dos

$
0
0

 For some reason I cannot get correct to equal 5 no matter what is typed in, is there a certain spot where it has to go? I know my input variable works, and the correct variable is what would make it change over to the tower, but whenever I try to key it in correct does not appear to change. Any help or advice is appreciated.

The Code:

int correct = 4;

string quest = "Insert Quest Here";

            #region
                if (correct == 4)
                {
                    do
                    {
                        //Inputs
                        #region
                        if (input == "1") { correct = 5; }
                        if (input == "NORTHEAST TOWER") { correct = 5; }
                        if (input == "TOWER") { correct = 5; }
                        if (input == "NORTHEAST") { correct = 5; }
                        if (input == "NORTHEASTTOWER") { correct = 5; }
                        if (input == "NORTH TOWER") { correct = 5; }
                        if (input == "GUARD TOWER") { correct = 5; }
                        #endregion

                        input = Console.ReadLine().ToUpper();

                        Console.Clear();
                        Console.WriteLine("General's Quarters");
                        Console.WriteLine("");
                        Console.ForegroundColor = ConsoleColor.DarkCyan;
                        Console.WriteLine(quest);
                        Console.ResetColor();
                        Console.WriteLine("");
                        Console.WriteLine("<NORTHWEST GUARD TOWER>");
                        Console.WriteLine("");
                        Console.WriteLine(correct);
                        Console.ReadLine();
                    } while (correct == 4);
                }
                #endregion

 //Northwest Tower - 5
                #region
                if (correct == 5)
                {
                    do
                    {
                        Console.Clear();
                        Console.WriteLine("Nortwest Tower");
                        Console.WriteLine("");
                        Console.WriteLine("<GENERAL'S QUARTERS>");
                        Console.WriteLine("<NORTHWEST TOWER ROOF>");
                        Console.WriteLine("<WESTERN BARRACKS>");
                        Console.WriteLine("");
                    } while (correct == 5);
                }
                #endregion

dynamic textbox textchanged event not firing

$
0
0

hello everyone,

i have this function

                    
protected object GridView3_focus()
    {

        DataView dv = (DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty);

        TextBox focusBox = new TextBox();
        //focusBox.Attributes.Add("onkeyup", "enter(this,1)");
        focusBox.Attributes["onkeyup"] = "enter(this,1)";
        //focusBox.Attributes.Add("onfocus", "this.select();");
        if (Int32.Parse(GridView3row.Value) > 0)
        {
            focusBox.Text = dv.Table.Rows[Int32.Parse(GridView3row.Value) - 1][1].ToString();
        }
        focusBox.Attributes["runat"] = "server";
        focusBox.Attributes["onfocus"] = "this.select();";

        focusBox.Attributes["OnTextChanged"] = "editCell";
        focusBox.AutoPostBack = true;


      //  focusBox.ID = "focusbox";
        focusBox.TextChanged += new EventHandler(editCell) ;

        if (Int32.Parse(GridView3row.Value) > 0)
        {
            GridView3.Rows[Int32.Parse(GridView3row.Value) - 1].Cells[Int32.Parse(GridView3column.Value) + 1].Text = "";
            GridView3.Rows[Int32.Parse(GridView3row.Value) - 1].Cells[Int32.Parse(GridView3column.Value) + 1].Controls.Add(focusBox);

        }

        //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DoPostBack", "__doPostBack(sender, e)", true);
        return 0;
    }


which creates a a textbox dynamically in a gridview based on if a cell has foucs or not. the problem is the textchanged event is not firing. i tried putting the code in page_load and the event fires from there but i need it to work from this function which gets called by in javascript by the way  

function focused(obj) {
                var tr = obj.parentNode.parentNode
                //alert("focused");
                document.getElementById("GridView3row").value = tr.rowIndex;
                documnet.getElementById("GridView3column").value = obj.parentNode.cellIndex;<%= GridView3_focus() %>


            }

Noob Query: For Loop Logic

$
0
0

for the life of me, I cannot figure this out.

static void fillarr3(int[] arr)
        {
            int in3 = 3;
            int x = 0;
            int y = 100 / 3;
            for (int i = 0; i < y; i++)
            {
                x = i * in3;
                arr[i] = x;
            }
        }

I'm trying to fill an array with the multiples of 3.  The problem is that an array starts with 0 index instead of 1.  So int i in the for loop must begin with a zero to properly place the number into the first index.  But I need the first index in the array to represent 1 instead of 0.  because 0 is not a multiple of 3.

The output should be 1, 3, 6, 9, etc, etc. instead it reads 0, 3, 6, 9, etc.

I know I can get around this by manually setting the first index, but i do not want to manually set any arrays.

C# code

$
0
0

Hi,

If I'm stuck with code, where do I get help?

could I get help here?

the problem too is I don`t know how to put 000.000.00.0 in the .next it won`t let it go in!

i must do this for the job entry:

You are the captain of a starship. You have been tasked with finding the 10 closest habitable planets to your home world and colonizing them.

Your home world is located at these coordinates: 123.123.99.1 X & 098.098.11.1 Y & 456.456.99.9 Z

Your coordinate system ranges from 000.000.00.0 to 999.999.99.9

1. Design and code an algorithm to randomly generate 15 000 coordinates. Each of these coordinates must be randomly marked as a planet or a very hungry space monster. (Space monsters eat starships and should be avoided at all costs)

- Each of these coordinates marked as a planet must be randomly marked as habitable or not.

- Each Habitable planet must have a surface area randomly ranging from 1 million to 100 million square kilometers.

- In order to inhabit a planet, you have to colonize more than 50% of it’s surface.

- Colonization takes place at exactly 0.43 seconds per square kilometer.

- Due to the strange construction of the star system you live in, travel time between any planet and its immediate neighbor is always 10 minutes

 Write the results to a txt file in a format of your choosing.

 2. Design and code an algorithm to read the file created in step 1 which will identify the planets you have to travel to and colonize to achieve the largest amount of colonized space within a 24-hour period.

 Give a detailed explanation of your thought processes used to solve the problem and clearly state any assumptions made.

 Complete your solution in a Visual Studio project using the C# programming language.

I do not know how to put it in it gives errors?




Chart Control ChartAreas[].CursorY.SetCursorPixelPosition...

$
0
0

I am having two problems with SetCursorPixelPosition in a chart control.

1.  I am using SetCursorPixelPosition to draw cross hairs on the chart control and to post X (normal scale) and Y Values (log scale) in a label on a form.  The values post correctly based on the cursor position, but the cross hair for the Y axis "jumps" or "sticks" at 10, 100, 1000 etc.  Does anyone have an idea on how to get the cursor to move smoothly?  No issues with XAxis cursor.

2.  I am getting an ArgumentException (Position argument should be in range from 0 to 100) when I move to the right edge of the ChartArea.  This is a mousemove event and is being thrown by a date axis - ChartAreas.AxisX.PixelPositionToValue(e.X). Any ideas on how to correct this exception or prevent it from happening.

Thank you in advance.

sort a list in C#

$
0
0

Hi ,

 I have an asp.net 4.5 with C# application, I have list. How can I sort the Below list with name and salary

List<Employee> empList = new List<Employee>()
   { 
 new Employee { Name = "a", Salary = "a-2" } ,
 new Employee { Name = "D", Salary = "ADC" } ,
 new Employee { Name = "D", Salary = "ABC" } ,
new Employee { Name = "a", Salary = "2-620-900-085" } ,                                             
  new Employee { Name = "a", Salary = "262-08-074" } ,
};

The expected output=>

 a a-2,a 262-08-074, a 2-620-900-085, D ABC, D ADC.

Thanks

Dileep

run visual c#2010 program on c#visual2016

$
0
0

Hello,

I have a piece of software running on a FEZ pandaII. Now i wonna convert it so it will run on a FEZ Panda III.

Please help.


convert string with variable to math expression and evaluate it

$
0
0

 i need to convert any string from user  to math expression such as                 ( x*x)/(a+b)-1 or any other 

and the variable get it from user or  i will put it in the program and output the result in screen

How to check if a variable with type int is null

$
0
0

I have an SQL table lilke this:

table: Employees
ID (int)	   Name (varchar)	Age (int)      Department
1	        John		30		Sales
2	        Smith	        NULL		Sales
3 	        Bob	        45		QC

I want to get the age of a specific employee. My C# code is as followed:

string str = "Select * from Employees";
SqlDataAdapter da = new SqlDataAdapter();
try
{
     SqlCommand sqlCmd = new SqlCommand(str, Conn);
     da.SelectCommand = sqlCmd;
}
catch (SqlException ex)
{
     MessageBox.Show(ex,ToString());
}
DataTable dt = new DataTable();
da.Fill(dt);

var age = from row in dt.AsEnumerable()
	where row.Field<int>("ID") == 2
	select row.Field<int>("Age");

If (age.FirstOrDefault<int>() != null)
	//do something
else
	//do something else

The problem with the If statement is that the condition is always true since a value of type 'int' is never equal to 'null', so it never goes to the 'else' part. I tried to change it to:

if (age.FirstOrDefault<int>() != 0)

but it still does not work. 

Note that this is a part of a larger code so using SqlCommand.ExecuteScalar is not an option for me, even though it may work. 






Window Smartscreen

$
0
0

how to protect my windows app from Window smart screen while downloading the app from server

Error Message

Windows Smart screen prevented an unrecognized app from starting.Running this app might put your PC at risk

Get javascript onClick function definition within webform

$
0
0
I'm developing a windows form application to parse and analyze web pages. I've used webbrowser control. The web page has html and javascript code bellow. and my windows form has c# code. Here is the code:

HTML code:
<div id="div1" onclick='func1(this);'></div><div id="div2"></div>
Javascript:
function func1(element) {
...
}
document.getElementById("div2").onclick = function foo() { doSomething(); }
C# code in my windows form application after navigating the related URL:
HtmlElement el1 = WebBrowser.Document.GetElementById("div1");
HtmlElement el2 = WebBrowser.Document.GetElementById("div2");
String el1JavaFunc = el1.GetAttribute("onClick");
String el2JavaFunc = el2.GetAttribute("onClick");
The result for both "el1JavaFunc" and "el2JavaFunc" is "System.__ComObject".

How could I get the assigned javascript function name? For instance get "func1" for "el1".

Should I use any other control instead of "WebBrowser"?

Please Note that I don't need to execute the events and I know that "System.__ComObject" is like a wrapper for "JavaScript" functions.

How to capture file delete in c#

$
0
0

i want to develop a c# apps which prevent a specific type of file delete. when user try to delete a specific type of file then my apps which show a password dialog and if user can give right pwd then file will be deleted, other wise not.

guide me how to write this kind of program by c# using win32 api. is it possible?

thanks

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>