Problem in Serial Interfacing with .net using C#

Hello, I am trying to send a string from my pc to arduino and receive the same from arduino using a windows form application in c#. Actually the whole idea is to make a Serial Monitor for myself which i can put to a lot more use than provided by arduino.
But, whats happening is when i am sending the data Arduino's bot rx and tx glows up, but i can't see any data on application itself, its a simple application but I am not able to figure out whats wrong on which side(Arduino code or c# code).
P.S I am using Arduino mega 2560

The code in c# is

using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication21
    public partial class Form1 : Form
        SerialPort myport = new SerialPort("COM4");
        public Form1()
            myport.BaudRate = 9600;
            myport.DataBits = 8;
            myport.Parity = Parity.None;
            myport.StopBits = StopBits.One;
            myport.Handshake = Handshake.None;
            myport.DataReceived += new SerialDataReceivedEventHandler(Form1.DataRecievedHandler);

        //Event for handling incoming serial data
        public static void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadExisting();

        private void button1_Click(object sender, EventArgs e)
            if (!myport.IsOpen)


Arduino Code:

#define MAX_MSG_LEN 20
void setup()

char inChar, buf[MAX_MSG_LEN];

int i = 0;

boolean flag;

void loop()

  flag = false; //Turns true if data is recieved


  // read incoming message
    flag = true;
    inChar = (char);
    if(inChar != '\n' && i != MAX_MSG_LEN)
      buf[i++] = inChar;

    delay(1); // wait for another byte


void Send(char *msg){

What do you see if you print inChar and buf when you receive a character on the Arduino ?

One thing that might be causing a problem is that the Arduino is reset every time the Serial port is opened.

Your C# code seems to open and close the serial port for every button press. That may be common practice for PC systems but it is entirely wrong for the Arduino.

Your PC program needs to open the serial port, and allow time for the Arduino to reset before it sends any data. Then it must keep the serial port open until the PC is completely finished with the Arduino.

This Python demo illustrates how that can be done. The same principles apply in any language.