mardi 31 mars 2015

"Procedure or function 'UPDATE' expects parameter '@Id', which was not supplied" in Windows Form

We created a Windows Form To Update a Table in SQL, First I Click Enter ID to retrieve Details from Database, then After changing some Data , when I click on Update Button , Its Give an error : "Procedure or function 'UPDATE' expects parameter '@Id', which was not supplied."


Windows Form Design :Click here


Error : Click here


Code For Windows :



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication12
{
public partial class Update : Form
{
string connectionString = @"Data Source=AMAR;Initial Catalog=Hotel;Integrated Security=True";

public Update()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
{
TestObject t = null;
string spName = "Get";
//string queryText = "Select * from TestTable where Id = " +txtId.Text;
SqlConnection conn = new SqlConnection(connectionString);
//SqlCommand com = new SqlCommand(spName, conn);
SqlCommand com = new SqlCommand(spName, conn);
com.Parameters.AddWithValue("@Id", ID.Text);
com.CommandType = CommandType.StoredProcedure;

conn.Open();
using (SqlDataReader reader = com.ExecuteReader())
{
t = new TestObject();
while (reader.Read())
{
t.Id = reader["ID"].ToString();
t.Status = reader["Status"].ToString();
t.FName = reader["FirstName"].ToString();
t.LName = reader["LastName"].ToString();
t.Addr = reader["Address"].ToString();
t.City = reader["City"].ToString();
t.State = reader["State"].ToString();
t.Country = reader["Country"].ToString();
t.PhoneNo = reader["PhoneNo"].ToString();
t.Email = reader["EmailId"].ToString();
t.Pin = reader["Pincode"].ToString();
t.CheckIn = reader["CheckIn"].ToString();
t.CheckOut = reader["CheckOut"].ToString();
t.AdultNo = reader["AdultNo"].ToString();
t.ChildNo = reader["InfantNo"].ToString();
t.InfantNo = reader["InfantNo"].ToString();
t.RoomNo = reader["RoomNo"].ToString();




};
}
Statustxt.Text = t.Status;
txtfName.Text = t.FName;
txtlName.Text = t.LName;
txtAddr.Text = t.Addr;
City.Text = t.City;
State.Text = t.State;
Country.Text = t.Country;
PhoneNo.Text = t.PhoneNo;
EmailID.Text = t.Email;
Pincode.Text = t.Pin;
CheckIN.Text = t.CheckIn;
CheckOut.Text = t.CheckOut;
Adult.Text = t.AdultNo;
Child.Text = t.ChildNo;
Infant.Text = t.InfantNo;
RoomNo.Text = t.RoomNo;




}
}

private void Update_Load(object sender, EventArgs e)
{

}

private void btnUpdate_Click(object sender, EventArgs e)
{

string Stat = Statustxt.Text;
string FirstName = txtfName.Text;
string LastName = txtlName.Text;
string Address=txtAddr.Text;
string Cities=City.Text;
string States= State.Text;
string Countries =Country.Text;
string PhoneNos= PhoneNo.Text;;
string EmailId= EmailID.Text;
string PinCode=Pincode.Text;
string CIn=CheckIN.Text;
string COut=CheckOut.Text;
string AdultNo=Adult.Text;
string ChildNo=Child.Text;
string InfantNo=Infant.Text;
string RoomNos=RoomNo.Text;


TestObject obj = new TestObject();

obj.Stat=Statustxt.Text;
obj.FirstName = txtfName.Text;
obj.LastName = txtlName.Text;
obj.Address=txtAddr.Text;
obj.Cities=City.Text;
obj.States= State.Text;
obj.Countries =Country.Text;
obj.PhoneNos= PhoneNo.Text;;
obj.EmailId= EmailID.Text;
obj.PinCode=Pincode.Text;
obj.CIn=CheckIN.Text;
obj.COut=CheckOut.Text;
obj.AdultNo=Adult.Text;
obj.ChildNo=Child.Text;
obj.InfantNo=Infant.Text;
obj.RoomNos=RoomNo.Text;


string spName = "UPDATE";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(spName, conn);
conn.Open();
com.Parameters.AddWithValue("@Stat", obj.Stat);
com.Parameters.AddWithValue("@FirstName", obj.FirstName);
com.Parameters.AddWithValue("@LastName", obj.LastName);
com.Parameters.AddWithValue("@Address", obj.Address);
com.Parameters.AddWithValue("@Cities", obj.Cities);
com.Parameters.AddWithValue("@States", obj.States);
com.Parameters.AddWithValue("@Countries", obj.Countries);
com.Parameters.AddWithValue("@PhoneNos", obj.PhoneNos);
com.Parameters.AddWithValue("@EmailId", obj.EmailId);
com.Parameters.AddWithValue("@PinCode", obj.PinCode);
com.Parameters.AddWithValue("@CIn", obj.CIn);
com.Parameters.AddWithValue("@COut", obj.COut);
com.Parameters.AddWithValue("@AdultNo", obj.AdultNo);
com.Parameters.AddWithValue("@ChildNo", obj.ChildNo);
com.Parameters.AddWithValue("@InfantNo", obj.InfantNo);
com.Parameters.AddWithValue("@RoomNos", obj.RoomNos);

com.CommandType = CommandType.StoredProcedure;


com.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Customer Details updated in system");

}
}


}


SQL STORE PROCEDURE:



USE [Hotel]
GO
/****** Object: StoredProcedure [dbo].[Insert] Script Date: 04/01/2015 11:24:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[UPDATE]
@Id int,
@Stat nvarchar(100),
@FirstName nvarchar(100),
@LastName nvarchar(100),
@Address nvarchar(100),

@Cities nvarchar(100),

@States nvarchar(100),
@Countries nvarchar(100),
@PhoneNos int,
@EmailId nvarchar(100),
@PinCode int,
@CIn nvarchar(100),
@COut nvarchar(100),
@AdultNo int,
@ChildNo int,
@InfantNo int,
@RoomNos int
AS
BEGIN
SET NOCOUNT ON;

-- Insert statements for procedure here
UPDATE [Hotel].[dbo].[Details] SET
[Status] = @Stat,
[FirstName] = @FirstName,
[LastName] = @LastName,
[Address] = @Address,
[City] = @Cities,
[State] =@States ,
[Country] = @Countries,
[PhoneNo] = @PhoneNos,
[EmailId] = @EmailId,
[Pincode] = @PinCode,
[CheckIn] = @CIn,
[CheckOut] = @COut,
[AdultNo] = @AdultNo,
[ChildNo] = @ChildNo,
[InfantNo] = @InfantNo,
[RoomNo] = @RoomNos
WHERE ID = @Id

END

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll in Winform C#

Can Anyone help me? I'm using SQL2014 and my code as below:



void loadProductsInfor()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"server=
.\SQLEXPRESS;database=CNET_Block3;
uid=sa;pwd=123456;integrated security=true";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Products";
**SqlDataReader dr = cmd.ExecuteReader(); (Exception appears at this line)**
while (dr.Read())
{
dataGridView1.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(),
dr[4].ToString(), dr[5].ToString(), dr[6].ToString(), dr[7].ToString(), dr[8].ToString(),
dr[9].ToString(), dr[10].ToString());
}
dr.Close();
con.Close();
}


I tried many things but they didn't work. I have a practical exam in the next 2 days. Please give me a hand.


Using a Winforms App to Configure a Windows Service

I have a single project made up of a Winform and a Windows Service. When installed, they both exist in the same, common folder, c:\program files\


I would like for the Winform to be able to set settings such as connection strings, passwords, logfile paths, etc. in a common xml file that both applications share. i will handle all of the encryption and decryption so that is not my issue.


The issue seems to be that when the application is installed, the Winform is unable to update the file and I get an access denied error although I am a COMPLETE domain admin with absolute rights over the desktop.


The question is, how does one go about allowing a Winform to define a common connection string between both the Winform application and the Windows service it wishes to configure?


I do NOT want to rely on the machine.config and want my own XML file that will hold all of the configuration options. There must be something simple I'm missing, a simple solution?


Show a form while BackgroundWorker is running

I want to display a "loading form" (a form with some text message plus a progressBar with style set to marquee) while the BackgroundWorker's job isn't done. When the BackgroundWorker is done, the loading form must be closed automatically. Although I do use a BackgroundWorker, the main thread should wait until it's done. I was able to do that using a AutoResetEvent but I noticied that as it does block the main thread, the form loading's progressBar is freezed too.


My question is: How can I show that form without freeze it while runing a process in background and wait for it finish? I hope it's clear.


Here's my current code:



BackgroundWorker bw = new BackgroundWorker();
AutoResetEvent resetEvent = new AutoResetEvent(false);
//a windows form with a progressBar and a label
loadingOperation loadingForm = new loadingOperation(statusMsg);
//that form has a progressBar that's freezed. I want to make
// it not freezed.
loadingForm.Show();

bw.DoWork += (sender, e) =>
{
try
{
if (!e.Cancel)
{
//do something
}
}
finally
{
resetEvent.Set();
}
};

bw.RunWorkerAsync();
resetEvent.WaitOne();
loadingForm.Close();

Reading all text files in a network path in a WinForms app

How can i read all the text files in a network path in C# Winforms?. The text files name are always changing.


example:



  • ABC-GD09538.txt

  • ADB-JK3949.txt

  • GJD-KGL9495-txt


The format of each text file when opened is:



Some Text
Some Text
Some Text
Some Text

[data start]
"Data1"|"Data2"|"Data3"|"Data4"|"Data5"|"Data5"|"Data6"
[data end]


I would also like to ignore the "some text" part of text file and proceed the text file reading on the line [data start] and end it on the line [data end] then finally perform a query to database and then insert the data received from text files to a table.


Draw border when the Control is focused

I use C# Windows Form to develop a program. Now, I want to draw a border on any Control which is focused, and the border has to be disappear when the control is lost focus. I try to use like below code to draw border, but I have no idea how can let the border painted before disappear.



void mButton_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, ((Control)sender).ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid);
}

Dynamic Windows Form Initialization

I am trying to write a program in C# that dynamically initializes a set of windows forms.


It's a tournament program that allows the user to manage multiple stations at once.


So, the best I've come up with is something like, say, the user wants to manage three stations.



TournamentForm[] T = new TournamentForm[3];

void startTournament()
{
for (int count = 0; count < t.length; count++)
{
T[count] = new TournamentForm();
T[count].show();
}
}


The inherent problem with this approach is that at the end of each loop, the form is closed.


Is there a means of dynamically initializing windows forms, or do I have to long code a maximum number of windows instances?




Hmm... I may have had an idea using recursion while writing this. Still posting the question in case there's a better answer.


ToolStripMenuItem: Add arrow without submenu

How can I add a menu item that has an arrow to the right as if there would be a submenu but does not show a submenu?


Background: For a managed C# application I want to add a submenu which is created in an unmanaged DLL (using TrackPopupMenu()).


In my experiments, I can only show the arrow when there are items attached using "DropDownItems.Add".


I tried to use



ToolStripMenuItem menu = new ToolStripMenuItem();
m_menu.Text = "Item that should have arrow w/o submenu";
m_menu.Click += this.OnMenuDoSomething;
m_menu.DropDownItems.Add("");


This still adds a submenu. I then tried these combinations:



m_menu.DropDownItems[0].Enabled = false;
m_menu.DropDownItems[0].Available = false;
m_menu.DropDownItems[0].Visible = false;


but either the submenu including the arrow disappears or nothing at all.


Remove icon automatically by dropped file on RichTextBox

I set to true the AllowDrop implemented the DragOver and DragDrop events RichTextBox. On DragDrop event I load the dropped text files' contents on the RTB but it does add the icon of the file in RTB I'd to remove it:


enter image description here


Edit: Here's my code:



void msg_setup_dragDrop()
{
msg_textBox.AllowDrop = true;


msg_textBox.EnableAutoDragDrop = true; msg_textBox.DragEnter += new DragEventHandler(msg_DragEnter); msg_textBox.DragDrop += new DragEventHandler(msg_DragDrop); }



void msg_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}

void msg_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
StringBuilder buffer = new StringBuilder();

foreach (string filename in files)
{
try
{
string text = File.ReadAllText(filename);
buffer.Append(text);
}
catch (Exception ex)
{
string errMsg = string.Format("cannot read the file\"{0}\" error: {1}", filename, ex.Message);
MessageBox.Show(errMsg, "Reading file error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}

msg_textBox.Text = buffer.ToString();
}

C#-4.0 Winforms inherited/sub-classed Button control OnClick not firing

In C# Winforms inherited/sub-classed Button control subscribing to OnMouseDown, OnMouseUp OnPaint and OnClick events. public class MyControl : Button The OnClick Event will not fire within the control or pass to the parent control the raised event. As soon as the the subclass is changed to type UserControl the OnClick event becomes active and the OnMouseDown, OnMouseUp, OnPaint events stop working within the control let alone within the parent. What can be done to force the control class to subscribe to the button control subclass's events when using the overrides? Supplied is the entire Class.



using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

namespace testbutton
{
public class EXButton : Button
{
MouseState state = new MouseState();
private Image _leftImage;
[Browsable(true), CategoryAttribute("Appearance"),
Description("Get/Set button Left Image"),System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)]
public Image LeftImage
{
get { return _leftImage; }
set
{
_leftImage = value;
this.Invalidate();
}
}

private Image _borderImage;
[Browsable(true), CategoryAttribute("Appearance"),
Description("Get/Set button Border Image"),System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)]
public Image BorderImage
{
get { return _borderImage; }
set
{
_borderImage = value;
this.Invalidate();
}
}

private Image _rightImage ;
[Browsable(true), CategoryAttribute("Appearance"),
Description("Get/Set button Right Image"),System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)]
public Image RightImage
{
get { return _rightImage; }
set
{
_rightImage = value;
this.Invalidate();
}
}

private Image _hoverIamge;
[Browsable(true), CategoryAttribute("Appearance"),
Description("Get/Set button Background Image of hover state"),System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)]
public Image HoverImage
{
get { return _hoverIamge; }
set
{
_hoverIamge = value;
this.Invalidate();
}
}

private Image _downIamge;
[Browsable(true), CategoryAttribute("Appearance"),
Description("Get/Set button Background Image of down/click state"),System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)]
public Image DownImage
{
get { return _downIamge; }
set
{
_downIamge = value;
this.Invalidate();
}
}

[Description("Extended Button Control")]
public EXButton()
{
this.InitializeComponent();
state = MouseState.Normal;
}

[Description("On Click event")]
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
MessageBox.Show("Button Clicked");
//This Message will only appear if the subclass is set to USERCONTROL
}

[Description("On Paint event")]
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

e.Graphics.Clear(this.BackColor);
if(_rightImage !=null) this.Height = _rightImage.Height;
if (state == MouseState.Normal)
{
if(BackgroundImage !=null ) e.Graphics.DrawImage(BackgroundImage, new Rectangle(0, 0, this.Width, this.Height));
}
if (state == MouseState.Enter)
{
if(_hoverIamge !=null) e.Graphics.DrawImage(_hoverIamge, this.ClientRectangle);
}
if (state == MouseState.Down)
{
if(_downIamge !=null) e.Graphics.DrawImage(_downIamge, new Rectangle(0, 0, this.Width, this.Height));
}
if(_rightImage !=null ) e.Graphics.DrawImage(_rightImage, new Rectangle(this.Width - _rightImage.Width, 0, _rightImage.Width, _rightImage.Height));
if(_leftImage !=null) e.Graphics.DrawImage(_leftImage, new Rectangle(0, 0, _leftImage.Width, this.Height));
if(_borderImage !=null) e.Graphics.DrawImage(_borderImage, new Rectangle(0, 0, this.Width, this.Height));

using (SolidBrush drawBrush = new SolidBrush(ForeColor))
{
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
e.Graphics.DrawString(Text, this.Font, drawBrush, new Rectangle(0, 0, this.Width, this.Height), format);
}
}


[Description("On Mouse Enter event")]
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
state = MouseState.Enter;
}

[Description("On Mouse Leave event")]
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseEnter(e);
state = MouseState.Normal;
}

[Description("On Mouse Click event")]
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
}

[Description("On Mouse Down event")]
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
state = MouseState.Down;
}

[Description("On Mouse Up event")]
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseDown(e);
state = MouseState.Enter;
}

#region Component Designer generated code
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}



/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}

#endregion
}

enum MouseState
{
Enter,
Normal,
Down
}
}


As you can see I have a MessageBox in the Controls OnClick event and the message never shows.



[Description("On Click event")]
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
MessageBox.Show("Button Clicked");
//This Message will only appear if the subclass is set to USERCONTROL
}


Thanks in advance for any responses.


Invalidate() custom control on every property change?

I am working on a custom winforms control that exposes a lot of properties that affect how the control looks (different colors for background, text and for different states like hover, click as well as icons etc). A change to one of these properties makes a repaint necessary so at the moment every property has a getter and setter with the setter calling Invalidate(). This is extremely annoying to code and if multiple properties are changed at once, every single one of them causes a repaint even though one repaint at the end would be enough.


I had the following ideas but I don't know if they are possible or how to implement them:



  1. cache property changes for a few milliseconds and then Invalidate()

  2. use some kind of reflection to detect whether the caller is going to change another property in the next line and if so delay the call to Invalidate()

  3. maybe some Attributes before the properties that make a repaint necessary or a List of all such Properties that is expanded to the getters/setters at compile time


Can you give me some advice if these ideas make sense/are possible and point me to how to implement them?


Deleting Specific Data From Database Row (C#)

I'm trying to allow (a user), to delete data from the database and replace it with updated information.


The problem I run into is this:



SqlException was unhandled: Incorrect syntax near ','.



And this error appears at the first: sqlcmd.ExecuteNonQuery()


Here is the full code for the "Apply Edits" button:



private void applybtn_Click(object sender, EventArgs e)
{
Connection();
sqlconnection.Open();

sqlcmd = new SqlCommand("DELETE Item, Quantity, description, datasheet FROM inventory_table WHERE id= " + ID, sqlconnection);
sqlcmd.ExecuteNonQuery();

sqlcmd = new SqlCommand("UPDATE inventory_table SET Item = @Item, Quantity = @Quantity, description = @description, datasheet = @datasheet "+
"WHERE id= " + ID, sqlconnection);
sqlcmd.Parameters.AddWithValue("@Item", this.txtbx1.Text);
sqlcmd.Parameters.AddWithValue("@Quantity", this.txtbx2.Text);
sqlcmd.Parameters.AddWithValue("@description", this.txtbx3.Text);
sqlcmd.Parameters.AddWithValue("@datasheet", this.txtbx4.Text);
sqlcmd.ExecuteNonQuery();

sqlconnection.Close();
}

Program runs in "Compatibility Troubleshooter" but not from desktop

Program developed in VS2010 was downloaded to a system running Windows 7 professional. The program started and ran for an hour before the system was shut down. Later the system was powered up again but the program would not launch from Startup, its desktop icon, or its folder. Ran the "Compatibility Troubleshooter" and the program started from there. Accepted the settings and went back to the folder but the program would not launch. Re-installed the program with same results. Why does it run from inside the troubleshooter b ut not the folder?


StreamWriter text file gets created but contains no lines

I'm trying to write some text lines to a little log file in a Windows Form application and I cannot see why no lines are written. The file gets created OK and all of the following executes without error but when I open the new file with Notepad, there are no lines. Key snippets follow:



Dim sFileName = App_Path() & "\logs\" & sJobName & ".log"
Try
Using fs As FileStream = New FileStream(sFileName, FileMode.Append, FileAccess.Write)
Using w As StreamWriter = New StreamWriter(fs)
Dim s As String = "Beginning execution (JobName=" & sJobName & ")"
Log(s, w)
s = "Connection in effect: " & BuildConnectString()
Log(s, w)
Dim loader As New Importer
loader.LoadData(Me.txtFN.Text, w)
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try

Public Sub Log(logMessage As String, w As StreamWriter)
w.WriteLine("{0} {1}: {2}", DateTime.Now.ToLongTimeString(), _
DateTime.Now.ToShortDateString(), logMessage)
End Sub


and then I'm trying to write to this log from a different class which has been passed the StreamWriter as a parameter:



Public Function LoadData(ByRef filename As String, _
ByRef w As StreamWriter) As String
Dim s As String = "Test logging from loader class"
Mainform.Log(s, w)


In this little test, I am expecting to see 3 lines but I'm getting nothing. I cannot see what I am doing wrong.


How to preview and print files (.pdf) in C# WindowsForms

I've this piece of code, and i want to print files, how can i do it? Preview and Print???


I've been trying several things to preview and print and this is the closest i've got!!



private void Imprimir()
{
PrintDocument pd = new PrintDocument();
pd.DocumentName = "Certificado de Abate IMTT";
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);

PrintDialog printdlg = new PrintDialog();
PrintPreviewDialog printPrvDlg = new PrintPreviewDialog();

// preview the assigned document or you can create a different previewButton for it
printPrvDlg.Document = pd;
printPrvDlg.ShowDialog(); // this shows the preview and then show the Printer Dlg below

printdlg.Document = pd;

if (printdlg.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
else
{
return;
}
}

private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
}

How to simulate ModelState.IsValid in C# winform application for any model validation

In asp.net mvc the people validate model this below way



using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models {
public class Movie {
public int ID { get; set; }

[Required]
public string Title { get; set; }

[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Required]
public string Genre { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

[StringLength(5)]
public string Rating { get; set; }
}

public class MovieDBContext : DbContext {
public DbSet<Movie> Movies { get; set; }
}
}

if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}


How could do the model validation same way in any C# win and webform application?


Update SelectedItem on ListView

I have a ListView that displays multiple rows of ListViewItems. The user is able to edit the row by clicking the edit button which opens up another form displaying the selected row and the data within it. The problem I am having is that I cannot seem to update the ListViewItem on the parent form when I press the update button. The code I am using keeps throwing the exception message "An unhandled exception of type 'System.NullReferenceException' occurred in ToDoList.exe". I have tried different approaches to updating the selected item but cannot seem to get a working code.


This is the code I am using on the form that displays the selected row, button1 is the "Update Row" button that should update the listView.



private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = (Form1)this.Owner;

int i = 0;
ListViewItem item = form1.listView1.SelectedItems[i];
textBox1.Text = item.SubItems[0].Text;
richTextBox1.Text = item.SubItems[1].Text;
comboBox1.Text = item.SubItems[2].Text;
dateTimePicker1.Text = item.SubItems[3].Text;

this.Close();
}

Reset the value of a group box?

first time asking a question here so sorry if I do something wrong


So here's my problem : I want to do a Tic Tac Toe program, and I have 9 buttons and 2 progress bar (for the score)


I want that when the progress bar X or Y does a PerformStep, all the 9 buttons (in a group box) resets to its initial value (Enable = true and Text = " ", because I disable it after the user clicked on it and the text changes for X or O depending of the player turn)


Is there a command that I can write for every buttons resets or I must do that one by one ?


Thanks you !


What makes it so that not every event is available in the designer, and how can I quickly generate handlers in C# like in VB.NET?

In the Visual Studio form designer, you can add an event handler on the Properties window in the "Events" list by double-clicking it. You can also add an event handler — at least in VB.NET — in the code view by selecting the associated "Events" item in the left-hand drop-down and then the desired event in the right-hand drop-down. My question is: how is it that some events that are only available via the latter technique and not the former? For example, the HandleCreated event is available in the code view:


enter image description here


But not in the designer:


enter image description here


This is fine in VB.NET because I can always use the first technique to quickly generate the event handlers. However, in C#, the first technique is not possible, yet the problem still exists; that is, some events are not present in the designer list in the Properties window. The only other way I know of creating the event handler is to manually add it, which includes manually wiring up the event handler.


Is there something technical that makes it so that some events are missing from the designer Events list in the Properties window? Given that that is true, how can I quickly generate event handlers in C# like I can in VB.NET?


Change color of edited text to red

I have gridview with five columns. i have loaded the data on it. the user can edit the text within the column cell. if the user edited the text,those edited text must be red. Only edited


e.g


stackoverflow = StackOverFlow (you will note that i have change/edited to caps. those edited caps must change color. in this case S O and F will change color to red)


this is what i have tried but not working the way



private void Gridview_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
if (cell.Tag != null && cell.Tag.ToString() != cell.Value.ToString())
cell.Style.ForeColor = Color.Red;
else
DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
cell.Tag = cell.Value != null ? cell.Value : "";

}

Move a control from a method in Windows Form

High level question, is it possible to move a control from a method? Example, I have a label and a button click event, can the label move from one position (X,Y) to another from the button click to something like (X+20,Y+20)?


I haven't had any luck with changing the .Position property of the label, and I couldn't find anything online so I thought I would ask. Thanks!


EDIT: Was asked to show some code so here ya go. The label1.Position can't be selected/edited, and label1.Move is an event handler, for when the user moves the label?



private void MoveTextButton_Click(object sender, EventArgs e)
{
label1.Position = (x,y);
//label1.Move
}

Emulating blocking Console keyboard input in a form

I need to write a console emulator in C#. I want to replace System.Console with something that can work in full-screen. My approach is to make a maximized Form with no borders.


One challenge I am facing is how to convert the event-driven, non-blocking keyboard input into a blocking one, or more specifically, how would you go about implementing an equivalent of Console.ReadKey() in a Windows Form.


Crystal Reports Viewer always uses WaitCursor

I have a Crystal Reports control that is embedded in a Winform. When the application is run, the WaitCursor (hourglass) is always shown over the Crystal Reports. Attempting to change the Cursor property for the Crystal Reports Viewer Control in the Property Pane of Visual Studio has no effect (the setting remains WaitCursor). Attempting to change the Cursor property in the Form_Load event of the Winform or the Load event of the Crystal Reports Viewer Control has no effect either.


Is there a way to force the cursor to Default when the mouse cursor is over the Crystal Reports Viewer Control? This is Crystal Reports 2008.


How to get dns name using Wmi

Hi I have a combobax control and populating it using this Wmi query.



ManagementObjectSearcher o = new ManagementObjectSearcher("select * from Win32_NetworkAdapter where PhysicalAdapter=true");
foreach (var v in o.Get())
{
cmbAdapters.Items.Add(v["Name"].ToString());
}


I am wondering how can I get Dns Server name or mybe SubnetMask information about a specificic adapter depends on selection from combobax .I think Win32_NetworkAdapterConfigurationclass is the right class for doing this but I have no idea how to do


How to pass EventArgs from View to Presenter in MVP?

I have an application based on MVP, WinForms and EntityFramework. At one form I need to validate cell value, but I don't know proper way to pass EventArgs from Validating event of DataGridView to my presenter.


I have this Form (unrelated code omitted):



public partial class ChargeLinePropertiesForm : Form, IChargeLinePropertiesView
{
public event Action CellValidating;

public ChargeLinePropertiesForm()
{
InitializeComponent();
dgBudget.CellValidating += (send, args) => Invoke(CellValidating);
}

private void Invoke(Action action)
{
if (action != null) action();
}

public DataGridView BudgetDataGrid
{
get { return dgBudget; }
}
}


Interface:



public interface IChargeLinePropertiesView:IView
{
event Action CellValidating;
DataGridView BudgetDataGrid { get; }
}


And this presenter:



public class ChargeLinePropertiesPresenter : BasePresenter<IChargeLinePropertiesView, ArgumentClass>
{
public ChargeLinePropertiesPresenter(IApplicationController controller, IChargeLinePropertiesView view)
: base(controller, view)
{
View.CellValidating += View_CellValidating;
}

void View_CellValidating()
{
//I need to validate cell here based on dgBudget.CellValidating EventArgs
//but how to pass it here from View?

//typeof(e) == DataGridViewCellValidatingEventArgs
//pseudoCode mode on
if (e.FormattedValue.ToString() == "Bad")
{
View.BudgetDataGrid.Rows[e.RowIndex].ErrorText =
"Bad Value";
e.Cancel = true;
}
//pseudoCode mode off
}
}


Yes, I could expose a property through interface and set my EventArgs to this property in View to get them from Presenter, but this is ugly, isn't it?


Can layout-adjusting statements be re-arranged in code generated by Designer?

In order to easily merge changes in *.Designer.vb files (the same applies to *.Designer.cs files), I need to sort content of certain code sections in files generated by Designer because Visual Studio is sometimes reordering them randomly. I can see 16 merge conflicts before rearranging, zero conflicts after.


I have no doubt on sorting declarations etc. But my doubt is about ResumeLayout(false) and PerformLayout() calls at end of InitializeComponent() method. Despite some learning, I don't fully understand yet how they work (practical details found here) and therefore I'm seeking an answer whether it is safe to re-arrange the order of objects they are called upon. Testing with Designer did not show problems so far but I'm asking to be sure.


Original order in Form1.Designer.vb



Private Sub InitializeComponent()

'...initializations of controls are left out

'
'Form1
'
Me.ClientSize = New System.Drawing.Size(784, 562)
Me.Controls.Add(Me.TableLayoutPanel1)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "Form1"
Me.Text = "Form1 Title"

'original order created by Designer
CType(Me.ErrorProvider1, System.ComponentModel.ISupportInitialize).EndInit()
Me.TableLayoutPanel1.ResumeLayout(False)
Me.TableLayoutPanel1.PerformLayout()
Me.page2.ResumeLayout(False)
Me.page2.PerformLayout()
Me.page1.ResumeLayout(False)
Me.TableLayoutPanel2.ResumeLayout(False)
Me.TableLayoutPanel2.PerformLayout()
Me.TabCtl1.ResumeLayout(False)
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
'end of section in question

Me.ResumeLayout(False)

End Sub


Modified order in Form1.Designer.vb



Private Sub InitializeComponent()

'...initializations of controls are left out

'
'Form1
'
Me.ClientSize = New System.Drawing.Size(784, 562)
Me.Controls.Add(Me.TableLayoutPanel1)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "Form1"
Me.Text = "Form1 Title"

'the following lines (or pairs) were arranged alphabetically - is it OK?
CType(Me.ErrorProvider1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
Me.page1.ResumeLayout(False)
Me.page2.ResumeLayout(False)
Me.page2.PerformLayout()
Me.TabCtl1.ResumeLayout(False)
Me.TableLayoutPanel1.ResumeLayout(False)
Me.TableLayoutPanel1.PerformLayout()
Me.TableLayoutPanel2.ResumeLayout(False)
Me.TableLayoutPanel2.PerformLayout()
'end of sorted groups

Me.ResumeLayout(False)

End Sub


Is such a change always safe? Or should the commands be arranged with respect to tree hierarchy of controls (parent listed first) instead of alphabetical ordering?


EDIT: some further research shows me, that form designer puts ancestors first, but enforces no other particular ordering. Order of controls is determined only by order of Control.Add() calls. Maybe I can improve sorting method to reflect this and I should be safe.


How to enable a button/combobox/textbox items while clicking an another button Visual C++

I am doing a small project in Visual C++. I am new to VC++. I am wondering, how can I enable a button or combobox or textbox items by clicking an another button in the same form?


Here in my form, I disabled the combo boxes for Power Line Frequency, Maximum Range, Measurement Rate Textbox, Apply button and Set parameters button.


The thing I have to do is enable the set parameters button when I click Init Button, and when I click Set Parameters button, the combo boxes for Power Line Frequency, Maximum Range, Measurement Rate Textbox, Apply button has to be enabled and finally, when I click the apply button, the values have to be updated in their respective fields and these combo boxes, textbox and apply has to be disabled.


Can anyone help me please to do these things?


Thanks in advance! Sorry, I am unable to upload the Image.


Winform with Splash Screen

I have a real strange problem with a winform application I am writing. I set up a splash screen using this example as a model: http://ift.tt/1BInxVI. Most of the time everything work fine but every once in a while the splash screen closes but leaves a white box on the screen where the splash screen was located. I have to reboot to get rid of the box. Does anyone have any ideas? This is a Windows 7 Pro PC.


Desktop after Splash Screen Closes


Running SSIS Package from WinForms app - Gnarly Error

I have a winforms application that makes use of Microsoft.SqlServer.ManagedDTS to load and execute an SSIS package. When running locally in debug and when installed the package runs fine, when installed on a dev server the package runs fine. When deployed onto a live server I get the following error.


Error Message


I'm running out of ideas of what to check, I don't want to move away from using this method of executing my package as this adds further complication to the application that we really don't want to introduce. Any thoughts?


For clarity I have checked:



  • SSIS is installed and is the same version (Windows/SQL Server 2008)


  • I added the following app.config key following some google searching useLegacyV2RuntimeActivationPolicy="true"




  • Tried compiling as a 32-bit and 64-bit application




  • Ensured that the DLL is registered in the GAC on the target machine




  • All permissions are the same across the two boxes




The extract of source code that is throwing the error is as follows:



var app = new Microsoft.SqlServer.Dts.Runtime.Application();
var pkg = app.LoadPackage(strSSISPath, null);
pkg.ImportConfigurationFile(strSSISConfig);

var result = pkg.Execute();

if (result.Equals(DTSExecResult.Success))
{
string strMsg = strMHType + " extract completed successfully.";
MessageBox.Show(strMsg, strMHType, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
foreach (var err in pkgMHMDS.Errors)
{
MessageBox.Show(err.Description, strMHType, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show(strMHType + @" extract failed!", strMHType, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
pkgMHMDS.Dispose();

PdfStamper is not being executed in C# WinForms

I've this piece of code bellow, but when it reaches to PdfStamper it stops the code, and leaves, giving nothing, not even an error.


What could be the solution for this problem?



private void FillForm()
{
try
{
string pdfTemplate = @"C:\Users\Diogo\Desktop\files\IMTT.pdf";
string newFile = @"C:\Users\Diogo\Desktop\P.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
pdfReader.SelectPages("1");
using (FileStream stream1 = File.Open(newFile, FileMode.OpenOrCreate))
{
PdfStamper pdfStamper = new PdfStamper(pdfReader, stream1); //stops here
AcroFields pdfFormFields = pdfStamper.AcroFields;

pdfFormFields.SetField("Nome.12", "TESTE");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
stream1.Close();
}
}
catch (Exception msg)
{
string m = msg.Message;
}
}

Having been working on JavaScript and Angular for the last year, I am currently working on a project in Winforms. I understand the cross thread issue with UI controls (InvokeRequired), but I haven't worked with BindingList before so to experiment I have a basic app that has a Form, Controller, and POCO that implements INotifyPropertyChanged. The Form gets injected with the controller, which has a BindingList. To simulate an outside thread manipulating the data, I have a Start method inside the Controller that creates a thread and runs a loop and updates the stock list. Obviously, this will raise the property changed event, which notifies the Grid and its datasource, however I get the cross thread exception. What I want to know what is the common practice for this? My past experience has been threads started from the GUI (background worker) and so the code is usually already in the Form and has access to 'this' to call InvokeRequired on. However when using BindingList from a Controller I don't have that.


Form1Controller



public class Form1Controller
{
public bool IsRunning { get; private set; }

private readonly Random _Random = new Random();

public Form1Controller()
{
Stocks = new BindingList<Stock>();
Stocks.Add(new Stock()
{
Name = "Microsoft",
Ticker = "MSFT",
Price = 25,
Volume = 100000,
LastTraded = DateTime.Now
});
Stocks.Add(new Stock()
{
Name = "Google",
Ticker = "GOOG",
Price = 450,
Volume = 100000,
LastTraded = DateTime.Now
});
Stocks.Add(new Stock()
{
Name = "Apple",
Ticker = "AAPL",
Price = 750,
Volume = 100000,
LastTraded = DateTime.Now
});
Stocks.Add(new Stock()
{
Name = "Oracle",
Ticker = "ORCL",
Price = 80,
Volume = 100000,
LastTraded = DateTime.Now
});
}

public BindingList<Stock> Stocks { get; set; }

public void Start()
{
IsRunning = true;

new Thread(() =>
{
while (IsRunning)
{
var index = _Random.Next(0, Stocks.Count);

Debug.WriteLine(index);

var stock = Stocks[index];
stock.Price += 1;
stock.Volume += 500;
stock.LastTraded = DateTime.Now;

Thread.Sleep(100);
}
}).Start();
}

public void Stop()
{
IsRunning = false;
}
}


Stock



public class Stock : DependencyObject
{
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, () => Name); }
}

private string ticker;
public string Ticker
{
get { return ticker; }
set { SetField(ref ticker, value, () => Ticker); }
}

private int price;
public int Price
{
get { return price; }
set { SetField(ref price, value, () => Price); }
}

private long volume;
public long Volume
{
get { return volume; }
set { SetField(ref volume, value, () => Volume); }
}

private DateTime lastTraded;
public DateTime LastTraded
{
get { return lastTraded; }
set { SetField(ref lastTraded, value, () => LastTraded); }
}
}


DependencyObject



public class DependencyObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}

protected virtual void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression)
{
if (selectorExpression == null)
throw new ArgumentNullException("selectorExpression");
MemberExpression body = selectorExpression.Body as MemberExpression;
if (body == null)
throw new ArgumentException("The body must be a member expression");
OnPropertyChanged(body.Member.Name);
}

protected bool SetField<T>(ref T field, T value, Expression<Func<T>> selectorExpression)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(selectorExpression);
return true;
}
}


Form1



public partial class Form1 : Form
{
private readonly Form1Controller _Controller = new Form1Controller();

public Form1(Form1Controller controller)
{
InitializeComponent();

_Controller = controller;
_MainGrid.DataSource = _Controller.Stocks;
}

private void _StartButton_Click(object sender, EventArgs e)
{
_Controller.Start();
}

private void _StopButton_Click(object sender, EventArgs e)
{
_Controller.Stop();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_Controller.Stop();
}
}


How do I marshal the property changed back onto the UI thread from the BindingList (assuming that is what I should be asking for)?


Subtracting Hours and Minutes from DateTime not working

I am trying to subtract hours and minutes from a DateTime variable and I have found other posts that show that you should be able to use the .AddHours(-3) in order to achieve this but it is not working for me. I am grabbing the datetime from a DateTimePicker control in vb.net. say the time is 10:00 AM, I want to subtract 3 hours from this to make it 7:00 AM. My hours variable evaluates to -3 but even when I just literally put the number -3 inside the .AddHours it still does not subtract the time. Heres the code



Dim ApptTime As DateTime = Convert.ToDateTime(DateTimePicker2.Value)
Dim travelTime As String = Label60.Text
Dim newtime As Double
Dim split() As String = travelTime.Split(" ")
If split.Length = 2 Then
Dim Minutes As String = split(0).Replace("mins", "")
Else
Dim Hours As Double = split(0).Replace("Hours", "")
Dim Minutes As Double = split(2).Replace("mins", "")
Hours = -Hours
Minutes = -Minutes
ApptTime.AddHours(Hours)
ApptTime.AddMinutes(Minutes)
Label62.Text = (ApptTime.ToString)

How to get all images from a url to picturebox in c#?

I want to display all images in picturebox from url in c#. Say your suggestion via syntax.


ControlPaint.DrawReversibleFrame - How am I supposed to erase drawn rectangle?

Consider the following code:



Dim recSelection As Rectangle?
Dim pntDown As Point?
Dim pntMove As Point?

Protected Overrides Sub OnMouseDown(e As Windows.Forms.MouseEventArgs)
MyBase.OnMouseDown(e)

pntDown = Me.PointToScreen(New Point(e.X, e.Y))
pntMove = pntDown
End Sub

Protected Overrides Sub OnMouseUp(e As Windows.Forms.MouseEventArgs)
If Me.recSelection.HasValue Then
ControlPaint.DrawReversibleFrame(recSelection.Value, Me.BackColor, FrameStyle.Dashed)
End If

pntDown = Nothing
pntMove = Nothing
recSelection = Nothing

MyBase.OnMouseUp(e)
End Sub

Protected Overrides Sub OnMouseMove(e As Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)

If pntDown.HasValue Then
If recSelection.HasValue Then
ControlPaint.DrawReversibleFrame(recSelection.Value, Me.BackColor, FrameStyle.Dashed)
End If

pntMove = Me.PointToScreen(New Point(Math.Max(Math.Min(e.X, Me.ClientSize.Width), 0), Math.Max(Math.Min(e.Y, Me.ClientSize.Height), 0)))

recSelection = GetRectangle(pntDown, pntMove)

ControlPaint.DrawReversibleFrame(Me.recSelection.Value, Me.BackColor, FrameStyle.Dashed)
End If
End Sub

Private Function GetRectangle(pointA As Point, pointB As Point) As Rectangle
Dim intLeft As Integer = Math.Min(pointA.X, pointB.X)
Dim intTop As Integer = Math.Min(pointA.Y, pointB.Y)

Dim intRight As Integer = Math.Max(pointA.X, pointB.X)
Dim intBottom As Integer = Math.Max(pointA.Y, pointB.Y)

Return Rectangle.FromLTRB(intLeft, intTop, intRight, intBottom)
End Function


Basically I want to draw a selection rectangle over a control and its children. In MSDN documentation, it says that to erase the rectangle, I should recall the DrawReversibleFrame method with the same parameters used to draw it in the first place.


Unfortunately, in my case that doesn't seem to work. The previous selection rectangle remains painted over the control. At one point I can end up having multiple selection rectangles accumulating:


enter image description here


(not the actual screenshot, I used MS Paint to reproduce the effect)


What am I doing wrong?


UPDATE:


I tried the very same code shown in the documentation and the behavior is the exact same! Might have something to do with my specific display settings. Also I'm using Windows 8.1. Could that be the issue? I'll try deploying on another system tomorrow.


Column Boundaries getting overlapped in Telerik Grid for Winforms

enter image description here


I am working on Winform application. Using Telerik controls on it.


On 1 form, I need to have composite columns as in image below. These columns have been added dynamically(through C#), I have used HTMlViewDefinition.


The problem is, columns boundaries are getting overlapped as in image below.


I need the column width to be decided at run time, so don't want to give static width to them.


Code, I have written for this grid is as below



var htmlView = new HtmlViewDefinition()
{

};
htmlView.RowTemplate.Rows.Add(new RowDefinition());
htmlView.RowTemplate.Rows.Add(new RowDefinition());

htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("No"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Item No"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("UOM"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Pres QTY"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Disp QTY"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Refill QTY"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Dose"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("No of Days"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("English Direction"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("No of Packs"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Drug Location"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Available QTY"));

htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Machine Available QTY"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Shelves Available QTY"));


htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Remain to Verify"));
htmlView.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Verification Status"));

htmlView.RowTemplate.Rows[0].Cells[0].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[3].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[4].RowSpan = 2;

htmlView.RowTemplate.Rows[0].Cells[3].ColSpan = 1;
htmlView.RowTemplate.Rows[0].Cells[4].ColSpan = 1;

htmlView.RowTemplate.Rows[0].Cells[5].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[6].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[7].RowSpan = 3;


htmlView.RowTemplate.Rows[0].Cells[9].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[10].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[11].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[12].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[13].RowSpan = 2;

htmlView.RowTemplate.Rows[0].Cells[14].RowSpan = 2;
htmlView.RowTemplate.Rows[0].Cells[15].RowSpan = 2;


htmlView.RowTemplate.Rows[0].Height = 30;

htmlView.RowTemplate.Rows[1].Cells.Add(new CellDefinition("Item Description"));
htmlView.RowTemplate.Rows[1].Cells[0].ColSpan = 2;
htmlView.RowTemplate.Rows[1].Cells.Add(new CellDefinition("Direction"));
htmlView.RowTemplate.Rows[1].Height = 30;
gridDrugList.BestFitColumns();

gridDrugList.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;

gridDrugList.ViewDefinition = htmlView;

Creating static Windows.Forms.Control

I have a project to which I delegate the function of creating a library of (static)? classes used in all my other projects. It is referenced via solution in these cases.


For instance, I have an extension which creates checkboxes within a given GroupBox's panel, and that works great:



public static void PreencheCheckboxesPanel(this Panel p, List<CheckBox> listaCheckBoxs) {
var count = 0;
listaCheckBoxs.ForEach(
i => {
i.Location = new Point(10, 10 + ((count) * 25)); //"dynamic" and not-so-effective resizing here
i.AutoSize = true;
count++;
});
p.Controls.AddRange(listaCheckBoxs.ToArray());
}}


Problem is, I need to insert a static checkbox on the top of the list, which will receive a method to (un)?check all the checkboxes below. So my code will become



public static void PreencheCheckboxesPanel(this Panel p, List<CheckBox> listaCheckBoxs) {
var count = 0;
if (adicionaAncora) {
CKB_ancora.Text = textoAncora;
CKB_ancora.CheckedChanged += (sender, args) => {
ChecaCheckBoxes(p, CKB_ancora.Checked);
};
listaCheckBoxs.Insert(0, CKB_ancora);
}
listaCheckBoxs.ForEach(
i => {
i.Location = new Point(10, 10 + ((count) * 25)); //"dynamic" and not-so-effective resizing here
i.AutoSize = true;
count++;
});
p.Controls.AddRange(listaCheckBoxs.ToArray());
}}


where ChecaCheckBoxes is another



public static void ChecaCheckBoxes(this Panel b, bool checkStatus = true) {
var listaCheckBoxs = (from Control c in b.Controls where c is CheckBox select (CheckBox)c).ToList();
listaCheckBoxs.ForEach(
i => {
i.Checked = checkStatus;
});
}


and CKB_ancora needs to be a solution-wide recognized object.


The reason? I have another extension named GetSelectedCheckBoxes which will be used to return all the checked ... ah... checkboxes within the groupbox. And, in order to make sure that the "anchor" (I call it like this, since I don't have a name to a (un)?check-all checkbox) won't be returned as well.


If I run this code, it will compile, but... will run accross an InvalidOperationException at Application.SetCompatibleTextRenderingDefault, right at Main(); Apparently, a control cannot be created/instantied before this method is run at mainpoint, which is the exact definition of "static".


Question: Knowing that I NEED a way to keep this particular check solution-wide visible... How do I do it?


Show datasource rows as columns on a DataGridView (Winforms)

I wanna show all my DataSource rows on a DataGridView, but not as rows but as columns of a row. Each 12 items retrieved, I wanna insert a new row on the DataGridView and populate this new row with more items from the DataSource (12 at each row).


My DataSource retrieves just one item each, and using it directly with the DataGridView is working nicely, but shown a different row for each item.


Any hints?


Change startup Enable / Disable options using .net applications

I have developed an application which will run at system startup. And it is working fine at system startup,i could see the application in System Configuration -> Startup. All the applications shown at Startup can be enabled / disabled.



But my question : is it possible to make an application which cannot be disabled at Startup ?


How are Startup properties controlled in registry?



The image shows an application which cannot be disabled at startup.


image


How to retrieve and change the actual height of Webbrowser DOM element dynamically

I try to change the height of an HtmlElment of a Webbrowser.Document


This is my code:



// when the element is rendered by browser
height = elem.OffsetRectangle.Height; // to get the height e.g 315
// here elem.ScrollRectangle height is the same as above

// setting it
IHTMLElement2 dom = elem.DomElement as IHTMLElement2;
dom.runtimeStyle.posHeight = height; // 315; // or
dom.runtimeStyle.height = height + "px";
// here elem.OffsetRectangle height is the same as height: 315
// but the elem.ScrollRectangle height is more 335!!!


After getting the height when I set the height to the same value (e.g 315), the offsetRectangle height has this value, but the actual height of the element decreases (As I check it visually), the ScrollRectangle height also changes.


Actually there is a mismatch between height I was read and the height I sat. The element has no padding or border.


What is the origin of this behavior? How can I get the height and change it or set it back to the original one with a consistent behavior?


Save datagridview into database - error occcured

I try to save the datagridview data into the database. But I don't know how to store it. I try some methods but it return error. So please I need to know how to rectify this error and my code is



string Stu_rollno = dataGridView1.Rows[i].Cells[1];
string sub_code = dataGridView1.Rows[i].Cells[2];


My error is;



Cannot implicity convert type 'system.windows.Forms.Datagridviewcell' to 'string'



Please give solution for this problem.


Windows Forms C#: Resize Label image on runtime when resizing the label

This is my issue:


I add labels to a form programmatically, including some properties to resize them on runtime by clicking and dragging them with the mouse right click event.


My situation is, that I add an empty label to contain an image from a given file through OpenDialog, and I would like to resize this image to fill the label size as I stretch the label. Unfortunately, I cannot set the size on runtime by accessing the image.Size property in the label, since it's read only... any ideas?


This is the affected piece of code:



Point _oldPosition;
public static Label _ctrlActiveControl;

if (e.Button == MouseButtons.Right)
{
_ctrlActiveControl.Cursor = Cursors.SizeNWSE;

//Code to resize the control based on the mouse position
Point newPosition = new Point(e.X, e.Y);
_ctrlActiveControl.Width += (newPosition.X - _oldPosition.X);
_ctrlActiveControl.Height += (newPosition.Y - _oldPosition.Y);

//Some security to make sure I don't shrink the control too much
if (_ctrlActiveControl.Width < 10) _ctrlActiveControl.Width = 10;
if (_ctrlActiveControl.Height < 10) _ctrlActiveControl.Height = 10;

//Here I check if the label contains an image and, if so, I should resize
//The image to "Autofill" the label
if (_ctrlActiveControl.Image != null)
{
Image image = _ctrlActiveControl.Image;
image.Size = new Size(_ctrlActiveControl.Width, _ctrlActiveControl.Height);
}

_oldPosition = newPosition;
}


I wonder if there's any way to do this, or should I instead use other control type (I know I can use others, but I'd like to know if there's any available workaround before adding more variables).


Array of reference (or pointer) to labels in c#

Say I have a form with a long bunch of temperature readouts, so in the designer:



this.lblTemperatureDevice01 = new System.Windows.Forms.Label();
this.lblTemperatureDevice02 = new System.Windows.Forms.Label();
this.lblTemperatureDevice03 = new System.Windows.Forms.Label();
// ...
this.lblTemperatureDevice50 = new System.Windows.Forms.Label();


In the main form code, how do I add the labels to an array so that I can update the labels using a loop in a timer event eg:



private void tmrUpdateLabels_Tick(object sender, EventArgs e)
{
// Disable timer
tmrUpdateLabels.Enabled = false;
if (m_bExiting)
return;

// Update temperatures (if device has returned a reading)
for (int device = 0; device < MAX_DEVICES; device++)
{
if (m_aHasNewReading[device])
{
m_aHasNewReading[device] = false;
labels[device].Text = m_aTemperature[device].ToString();
}
}

// Restart timer
tmrUpdateLabels.Enabled = true;
}


How do I create the labels[MAX_DEVICES] array? Must I use:



private Label[] labels = new Label[MAX_DEVICES];


or is there a way to get a reference (or pointer) to the existing label(s) without creating new labels? Coming from a C++ background where I might have simply stored the address of each label in an array.


How to show text at the center of the TextBox in Windows Forms

I have the multiline TextBox control in Windows Forms application and I want to show some text at the center of the TextBox area (both horizontally and vertically). How can I achieve such behavior?


Thanks in advance.


ADO.NET TableAdapter Updating on CellValueChanged Event for a DataGridView

I have a DataGridView which includes a checkbox column for a Boolean variable in the database.


When I click on this checkbox, it fires the events below.


Inside the uiPersonGridView_CellValueChanged event, I call the Data Table Adapter Update method on the Persons Data Table which is the Datasource for the DataGridView.


The Update works fine, the second time but it will still not Update the Current Rows Data?


For example, if I had two rows, if I tick in the first rows check box; Update returns 0 rows updated for int i and I check the database and nothing has been changed. But if I tick on the second rows check box, the Update returns 1 row updated for int i - I check the database and the first record has changed and not the second?


How can I get it work so the update works for the initial change and changes thereafter?



private void uiPersonGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (uiPersonGridView.IsCurrentCellDirty)
{
uiPersonGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

private void uiPersonGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (uiPersonGridView.DataSource == null)
return;

if (e.RowIndex == -1)
return;

int i = _personAdapter.Update(_person);
}

Is there any way to change the background color of the ComboBox control with DropDownList in Windows Forms

Is there any way to change the background color of the ComboBox control with DropDownStyle = DropDownList in Windows Forms?


If I just do



this.comboBox.BackColor = Color.Red;


nothing changed.


I need to highlight this ComboBox when the user doesn't choose any item (I can't provide the default item in my case).


Thanks in advance.


Invoke Drop event from code in C#

How to invoke DragDrop event from code in winforms.



var ctrls = this.Owner.Controls.Find("mediaPlayer", true);
ctrls[0].??DragDrop(x,y)??


Thanks in Advance.


How to pass data from one form to another?

I'm building a C# application which has to retreive a table data from my local database & display it on the form1, the form1 contains a separate button for Email function when i click on the Email button a new form form2 is opening through which a email can be sent & it contains To,cc,subject & message body, i want the retrieved data from database to be displayed in message body & the same data to be sent to the mail ids when i click on send button.


Currently I'm able to retrieve a data in form1 & from form2 i'm able to send a email successfully.


Can someone tell me how can i bring the data on form1 to form2 directly to message body of the Email


Form1 code



private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}


private void exitBtn_MouseClick(object sender, MouseEventArgs e)
{
this.Close();
}
private void submitBtn_MouseClick(object sender, EventArgs e)
{
try
{
String str = "server=localhost;port=3306;database=demo;UID=root;password=admin1234";
String query = "select * from demo.cstdetails;";
MySqlConnection con = new MySqlConnection(str);
MySqlCommand cmd = new MySqlCommand(query);
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter(query, str);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
//MessageBox.Show("connect with sql server");
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);

}
}

public void sql_conn()
{
throw new NotImplementedException();
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{

}

private void emailBtn_Click(object sender, System.EventArgs e)
{
email frm = new email();
frm.Show();
}


}


Form2 Code



private void sndBtn_Click(object sender, EventArgs e)
{
// MessageBox.Show("This is sendbutton");
try
{
SmtpClient server = new SmtpClient("smtp.gmail.com");
server.Port = 587;
server.EnableSsl = true;
server.Timeout = 100000;
server.DeliveryMethod = SmtpDeliveryMethod.Network;
server.UseDefaultCredentials = false;
server.Credentials = new NetworkCredential("user", "password");
MailMessage msg = new MailMessage();
msg.To.Add(textBox_To.Text);
msg.From = new MailAddress("mytest@gmail.com");
msg.Subject = textBox_Subject.Text;
msg.Body = dataGridView1.DataSource = ds.Tables[0].DefaultView;
try
{
String str = "server=localhost;port=3306;database=demo;UID=root;password=admin1234";
String query = "select * from demo.cstdetails;";
MySqlConnection con = new MySqlConnection(str);
MySqlCommand cmd = new MySqlCommand(query);
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter(query, str);
DataSet ds = new DataSet();
sda.Fill(ds);
//MessageBox.Show("connect with sql server");
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);

}
//Attachment data = new Attachment(textBox_Attachment.Text);
// msg.Attachments.Add(data);
server.Send(msg);
MessageBox.Show("Successfully Sent Message.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dscrdBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void dscrdBtn_MouseClick(object sender, MouseEventArgs e)
{
this.Close();
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}
}

lundi 30 mars 2015

Windows form hidden web browser control does not bring the IE window to foreground

I have created add in for outlook 2013. It has got a hidden web browser control within it. ON button click Web browser loads the speciified data inInternet explorer window. Content is loading but the IE window does not come to foreground and my outlook will continue be in focus. IE keeps blinking at the task bar.


I want the IE window be in foreground .


Please help, very urgent Thanks in advance


Catching exceptions thrown from UserControl in parent Form?

I have a Form that extends some class that has special exception-handling logic to present any that arise to the user in a clean manner. That Form contains a custom UserControl that has the potential to throw Exceptions which, if unaddressed, aren't caught and rethrown by the parent Form, and therefore don't hit the special logic.


How can I hook things up so that my UserControl throws exceptions to my Form?


how to put a webhostdatabase connection string in a winform application?

i have myself tried a lot but i couldn't find out what is the problem of my below connection string. i have put both my webhost connection string and winform connection string help please?



<connectionStrings> <add name="ReGdbEntities" connectionString="metadata=http://res*/Model1.csdl|res*/Model1.ssdl|res*/Model1.msl;
provider=System.Data.SqlClient;
provider connection string="data source=.\SQLEXPRESS;
initial catalog=ReGdb;
integrated security=True;
MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>


and here is my webhostdatabase connectionstring



Data Source=SQL5000322.Smarterasp.net;
Initial Catalog=DB_9BDB7789_ReGdb;
User Id=DB_9BDB7789_ReGdb_admin;
Password=happy;

Application Exit Control

I have created a Windows Application using C# (.NET Framework v4.0). The application purpose is a variety of Third Party Application API Integration into a single one.


Currently, I am facing an issue where the client starts the API requests. Due to some reason like Internet slowness the API Response takes a bit longer. The Client closes the application using the Red Application Exit Button or in some rare cases uses Task Manger to exit the application.


Issue now persists like, the API Request is processes succesfully in their side but before the response has been read in our side the Application has been closed and looses the thread and does not reflect in our side.


Is there any method through which we can control this application Exit ? Can we block this application exit especially when the API Reqest is in process.


Solution Under Implementation



  • Use a Global Variable when the application API Request is in progress.

  • Use the MDI Form OnClosing event trigger to check the status of the variable and block the Application Exit.


This method will not block, Task Manager application exit.


Is there any possible method which can be implemented to block this issue or a better method which can substantially reduce this specific error from my application.


Config file check if existing; encounters an unhandled exception

my senior gave me an assignment in which if app.config is missing (deleted by user, perhaps) then a new config file would be created (of course, with the same configuration as the old one).


So I googled and searched stack regarding this one and I found this with the same situation as I am now so I followed the answer given to the OP in that post. Done and done, build and run. I sent the exe file with the DLLs to my friend to test it and I made sure that MyApp.EXE.config is not included in the folder to test if it would work.


The result was that upon clicking MyApp.exe the first time, we didn't encounter any problems. So my friend clicked a button to open a file dialog and select a file, we encountered a dialog box containing a message regarding "Unhandled exception..." When I read over the details of the message, I saw these:



System.NullReferenceException: Object reference not set to an instance of an object.

at WindowsFormsApplication1.Form1.browsecfg_Click(Object sender, EventArgs e)

at System.Windows.Forms.Control.OnClick(EventArgs e)



and a bunch of other stuff and there's the JIT debugging as well.


We closed the app and opened it again and now before the form shows up, we got another dialog box about unhandled exception and it contains these details:



>System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section AppSettings. (C:\Users\uidr3024\Desktop\SVT_Tool\Continental.exe.config line 20)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.get_AppSettings()
at WindowsFormsApplication1.Form1.ConfigurationFile()
at WindowsFormsApplication1.Form1.Form1_Load_1(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)


This is the code on creating a new config file if it doesn't exist:



public void ConfigurationFile()
{
string path1;
string path2;
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["cfgPath"]))
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.AppendLine("<configuration>");
sb.AppendLine("<system.windows.forms jitDebugging=\"true\"/>");
sb.AppendLine("<runtime>");
//something else written inside runtime
sb.AppendLine("</runtime>");
sb.AppendLine("<AppSettings>");
sb.AppendLine("<add key=\"cfgPath\" value=\"\"/>");
sb.AppendLine("<add key=\"xmlPath\" value=\"\"/>");
sb.AppendLine("</AppSettings>");
sb.AppendLine("</configuration>");
string loc = Assembly.GetEntryAssembly().Location;
System.IO.File.WriteAllText(String.Concat(loc, ".config"));
}
else
{
path1 = config.AppSettings.Settings["cfgPath"].Value.ToString();
textBox1.Text = path1;
path2 = config.AppSettings.Settings["xmlPath"].Value.ToString();
textBox2.Text = path2;
}
}


And this is the original app.config:



<?xml version="1.0"?>
<configuration>
<system.windows.forms jitDebugging="true"/>
<runtime>
//something else written inside runtime
</runtime>
<appSettings>
<add key="cfgPath" value=" "/>
<add key="xmlPath" value=" "/>
</appSettings>
</configuration>


The AppSettings keys cfgPath and xmlPath are the paths of the last selected files from the file dialog box and is stored in the config file. The values of the keys would then be written on their respective textboxes (so the user would see what's the last file selected the next user opens the app). But when I checked the config file, it's not stored there and the values remain to be blank and the textboxes are blank as well.


Am I doing all of these right? Or are there any other ways to do this?


Animate Richtext Box using scrolbar in c# [on hold]

I have a richtext box in which data is added after every 3-4 minutes,


I want that scrol bar should auto scrol up and down so that it creates a animated effect ...


Which event is fired when I navigate to any other application in my PC?

I have a Custom Control of following type in .NET C# Winforms



public partial class AutoSuggestPopupList : ToolStripDropDown
{
}


It has got all its properties and methods. I am using it with a ListBoxControl and a textbox/combobox.


It is used in following manner: 1. As user types something in textbox/combobox 2. the list of ListBoxControl is refreshed and accordingly the items of AutoSuggestPopupList are refreshed.


I am closing my AutoSuggestPopupList in different Event Handlers and it gets closed appropriately. But my only problem is when I navigate to any other software like Word or Excel from my App, the AutoSuggestPopupList is not closed and is fixed at its location.


I have already tried using frm_LocationChanged and frm_VisibleChanged Event Handlers, but of no use :(


It will be a great help if some one can tell me which event handler will be useful for me , when i navigate to any other software.


How can I find File name in string which start with # Using RegEx

I have string :



" testfile.txt #testfile.txt
My new message
Filename1.doc #filename.doc"


How can I find file name starting with '#' and remove it from string


F# Winforms Charting Asynchronous Updating

I'm trying to create a chart in winforms that databinds to a list in memory, and gets updated dynamically as the list changes. Here is my code:



open System
open System.Linq
open System.Collections
open System.Collections.Generic
open System.Drawing
open System.Windows.Forms
open System.Windows.Forms.DataVisualization
open System.Windows.Forms.DataVisualization.Charting

let link = new LinkedList<double>()
let rnd = new System.Random()
for i in 1 .. 10 do link.AddFirst(rnd.NextDouble()) |> ignore
let series = new Series()
let chart = new System.Windows.Forms.DataVisualization.Charting.Chart(Dock = DockStyle.Fill, Palette = ChartColorPalette.Pastel)

series.Points.DataBindY(link)

let form = new Form(Visible = true, Width = 700, Height = 500)
form.Controls.Add(chart)

let formloop = async {
while not chart.IsDisposed do
link.AddFirst((new System.Random()).NextDouble()) |> ignore
link.RemoveLast()
}
do
Async.StartImmediate(formloop)
Application.Run(form)

Console.WriteLine("Done")
Console.ReadLine() |> ignore


The async seems to work, but the chart never shows anything. It just shows a blank window. What am I doing wrong?


Application.DoEvents Never Exits

I'm working on a legacy application which has sprinklings of Application.DoEvents here and there. I'm fully aware that this is frowned upon due to re-entrancy issues, but re-factoring isn't currently an option.


An issue has started to occur where DoEvents never exits. The UI is responsive (I can see UI thread activity in the user logs) so DoEvents seems to be pumping the messages, but for some reason it never completes. Unfortunately this DoEvents is in the main data-processing component, which means this stops processing server responses as it's stuck on the DoEvents line.


We have Stopwatch trace which tells how long the DoEvents ran for - staggeringly I got a log where it said it was running for 188267770 milliseconds, which is 52 hours (gulp). It seemed to get into this state at about 3am on a Saturday, until the user came in on Monday and shut the app down (not killing the process, I can see the GUI thread trace closing things gracefully), at which point the DoEvents completes and the timer data is logged (so something which happens during shutdown must convince DoEvents to complete).


Of course, this only happens on the production user's machines, and not on my dev box :)


Has anyone ever seen a similar problem to this?


I've decompiled DoEvents and also how Conrol.BeginInvoke pushes method delegates onto the GUI thread using the Windows message queue, but I cannot see how DoEvents can get stuck like this, and keep the UI responsive.


Source control diff is also not an option since there's been around 30 versions since the last 'good' version the users had, and this new version with the problem - so about 200 files have changed.


Many thanks Paul


How to assign one chart to another C#

I'm attempting to open a chart in another window form, however the classes used for the data in the chart is in the first form. My goal here is to have a chart be able to open many times in a modeless window.


in form1.cs I build my chart:



Chart chart = new Chart();
Series price = new Series("Price"); //create new series
chart.Series.Add(price);

chart.Series["Price"].ChartType = SeriesChartType.Candlestick;

chart.Series["Price"]["OpenCloseStyle"] = "Candlestick";

chart.Series["Price"]["ShowOpenClose"] = "Both";


chart.Series["Price"]["PriceUpColor"] = "Green"; //Price increase = green
chart.Series["Price"]["PriceDownColor"] = "red"; //price decrease = red

for (int i = 0; i < data.Count; i++)
{
chart.Series["Price"].Points.AddXY(data[i].getDate(), data[i].getHigh()); //Adds date and high value
chart.Series["Price"].Points[i].YValues[1] = System.Convert.ToDouble(data[i].getLow()); //Low value added to chart
chart.Series["Price"].Points[i].YValues[2] = System.Convert.ToDouble(data[i].getOpen()); //open value added to chart
chart.Series["Price"].Points[i].YValues[3] = System.Convert.ToDouble(data[i].getClose()); //close value added to chart
}


Form2.cs:



public void DisplayChart(Chart newChart)
{
chart1 = newChart;
chart1.Show();
}