تاپیک جامع نکات در سی شارپ
پر کردن لیست باکس با رنگ های سیستمی
کد:
private void Form1_Load(object sender, EventArgs e)
{
string[] colorNames;
colorNames = System.Enum.GetNames(typeof(KnownColor));
listBox1.Items.AddRange(colorNames);
}
به دست آوردن اختلاف دو تاریخ
کد:
using System;
namespace diffrenceDate
{
class Program
{
static void Main(string[] args)
{
DateTime firstDate = new DateTime(2000, 01, 01);
DateTime secondDate = new DateTime(2000, 05, 31);
TimeSpan diff = secondDate.Subtract(firstDate);
TimeSpan diff1 = secondDate - firstDate;
String diff2 = (secondDate - firstDate).TotalDays.ToString();
Console.WriteLine(diff1);
Console.ReadLine();
}
}
}
خواندن تمام خطوط یک فایل و قرار دادن در آرایه
کد:
using System;
namespace PlayingAround
{
class ReadAll
{
public static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(@"C:t1");
Console.Out.WriteLine("contents = " + lines.Length);
Console.In.ReadLine();
}
}
}
گرفتن ScreenShot از صفحه نمایش
کد:
private void button1_Click(object sender, EventArgs e)
{
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
Graphics Graphics1;
Bitmap Bitmap1 = new Bitmap(screenWidth, screenHeight);
Graphics1 = Graphics.FromImage(Bitmap1);
Graphics1.CopyFromScreen(Point.Empty, Point.Empty, Screen.PrimaryScreen.Bounds.Size);
Bitmap1.Save(@"c:\1.bmp");
}
افزودن تصویر در جلوی هر سطر Datagridview
کد:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Columns.Add("Column1", "Column1");
this.dataGridView1.Columns.Add("Column2", "Column2");
this.dataGridView1.Columns.Add("Column3", "Column3");
DataGridViewImageColumn img = new DataGridViewImageColumn();
Image image = Image.FromFile(Application.StartupPath + "\\0079.png");
img.Image = image;
img.HeaderText = "Image";
img.Name = "img";
dataGridView1.Columns.Add(img);
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
this.dataGridView1.Rows.Add(new object[] { 1, 2, 3 });
}
}
}
خروجی به شکل زیر میشه
تست اتصال یا عدم اتصال اینترنت
کد:
using System.Net;
using System.Net.NetworkInformation;
private String Getvalue;
private void button1_Click(object sender, EventArgs e)
{
try
{
WebClient IsState = new WebClient();
Getvalue = IsState.DownloadString ("http://www.google.com");
MessageBox.Show("Connect");
}
catch (Exception ex)
{
MessageBox.Show("Disconnect");
}
}
ویرایش عنوان گره های treeView در زمان اجرا
کد:
private void Form1_Load(object sender, EventArgs e)
{
TreeNode treeNode = new TreeNode("Windows");
treeView1.Nodes.Add(treeNode);
treeNode = new TreeNode("Linux");
treeView1.Nodes.Add(treeNode);
TreeNode node2 = new TreeNode("C#");
TreeNode node3 = new TreeNode("VB.NET");
TreeNode[] array = new TreeNode[] { node2, node3 };
treeNode = new TreeNode("www.ashiyane.org", array);
treeView1.Nodes.Add(treeNode);
}
private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.E)
{
treeView1.LabelEdit = true;
TreeNode editNode = treeView1.GetNodeAt(
treeView1.PointToClient(System.Windows.Forms.Control.MousePosition));
if (editNode != null)
{
editNode.BeginEdit();
}
}
}
private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
treeView1.LabelEdit = false;
}
Textbox ی که فقط فارسی در آن تایپ شود
کد را در رویداد KeyPress کنترل Textbox قرار دهید.
کد:
if ((e.KeyChar > 199 || e.KeyChar < 237)
&& (e.KeyChar < 1574 || e.KeyChar > 1594 && e.KeyChar < 1601 || e.KeyChar > 1608)
&& e.KeyChar != 1662 && e.KeyChar != 1668 && e.KeyChar != 1670 && e.KeyChar != 1705
&& e.KeyChar != 1711
&& e.KeyChar != 1740 && e.KeyChar != 8 && e.KeyChar != 32)
{
e.Handled = true;
}
ریختن مقادیر سلول های DataGridView در TextBox
کد:
using System;
using System.Windows.Forms;
namespace DGAndTextBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Columns.Add("Column1", "Column1");
this.dataGridView1.Columns.Add("Column2", "Column2");
this.dataGridView1.Columns.Add("Column3", "Column3");
this.dataGridView1.Rows.Add(new object[] { "Ottima", "Ottima1", "20" });
this.dataGridView1.Rows.Add(new object[] { "ali_Eagle", "Ottima2", "30" });
this.dataGridView1.Rows.Add(new object[] { "iman_taktaz", "Ottima3", "31" });
this.dataGridView1.Rows.Add(new object[] { "spoof", "Ottima4", "30" });
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
}
}
نمایش هشدار قبل از حذف یک سطر از DataGridView
کد:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Columns.Add("Column1", "Column1");
this.dataGridView1.Columns.Add("Column2", "Column2");
this.dataGridView1.Columns.Add("Column3", "Column3");
this.dataGridView1.Rows.Add(new object[] { "Ottima", "spoof", "20" });
this.dataGridView1.Rows.Add(new object[] { "Alireza Attacker", "4rm4n", "30" });
this.dataGridView1.Rows.Add(new object[] { "Nc 521", "Azad", "31" });
this.dataGridView1.Rows.Add(new object[] { "Pr0grammer", "Rezahck23", "30" });
}
private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
if (!e.Row.IsNewRow)
{
DialogResult res = MessageBox.Show("آیا از حذف این سطر مطمئن هستید؟", "Delete confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (res == DialogResult.No)
e.Cancel = true;
}
}
}
}
تغییر در ترتیب نمایش ستون های DataGridView
کد:
dataGridView1.Columns["Column1"].DisplayIndex = 1;
dataGridView1.Columns["Column2"].DisplayIndex = 0;
dataGridView1.Columns["Column3"].DisplayIndex = 2;
فارسی کردن زبان کیبورد هنگام اجرای برنامه
کد:
private void Form1_Load(object sender, EventArgs e)
{
InputLanguage.CurrentInputLanguage =
InputLanguage.FromCulture(System.Globalization.CultureInfo.CreateSpecificCulture("fa-IR"));
}
خواندن یک فایل متنی و قرار دادن آن در داخل یک رشته
کد:
using System;
namespace ReadAllText
{
class Program
{
static void Main(string[] args)
{
string contents = System.IO.File.ReadAllText(@"C:\Text.txt");
Console.Out.WriteLine("contents = " + contents);
Console.ReadLine();
}
}
}
به دست آوردن تعداد خطوط یک فایل متنی
کد:
using System;
namespace ReadAllLines
{
class Program
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(@"C:\Text.txt");
Console.WriteLine("contents = " + lines.Length);
Console.ReadLine();
}
}
}
حذف پوشه تکراری
کد:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter path1");
string pth1 = Console.ReadLine();
Console.WriteLine("enter path2");
string pth2 = Console.ReadLine();
string[] dir1 = Directory.GetDirectories(pth1);
string[] dir2 = Directory.GetDirectories(pth2);
string[] fil1 = Directory.GetFiles(pth1);
string[] fil2 = Directory.GetFiles(pth2);
int s = 0,f=0;
///compare directories
for (int i = 0; i < dir1.Length; i++)
{
for (int j = 0; j < dir2.Length; j++)
{
string d1 = dir1[i].Substring(dir1[i].LastIndexOf('\\'));
string d2 = dir2[j].Substring(dir2[j].LastIndexOf('\\'));
if (0==d1.CompareTo(d2))
s++;
}
}
///compare files
for (int i = 0; i < fil1.Length; i++)
{
for (int j = 0; j < fil2.Length; j++)
{
string f1 = fil1[i].Substring(fil1[i].LastIndexOf('\\'));
string f2 = fil2[j].Substring(fil2[j].LastIndexOf('\\'));
if (0 == f1.CompareTo(f2))
f++;
}
}
if (s == dir1.Length && s == dir2.Length && f == fil1.Length && f == fil2.Length)
{
Directory.Delete(pth2, true);
Console.WriteLine("deleted");
Console.ReadKey();
}
else
{
Console.WriteLine("not deleted");
Console.ReadKey();
}
}
}
}
به دست آوردن ابعاد صفحه نمایش
کد:
using System.Windows.Forms;
کد:
MessageBox.Show("Monitor Size:" + SystemInformation.PrimaryMonitorSize);
حذف تگ های HTML از رشته در سی شارپ
کد:
using System;
using System.Text.RegularExpressions;
namespace StripHTML
{
class Program
{
const string HTML_TAG_PATTERN = "<.*?>";
static string StripHTML(string inputString)
{
return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
}
static void Main(string[] args)
{
Console.WriteLine(StripHTML("<h1>This is Test</h1>"));
Console.ReadLine();
}
}
}
Arrow Minimize شدن فرم به System tray در هنگام بسته شدن
کد:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason ==CloseReason.UserClosing)
{
e.Cancel = true;
this.Visible = false;
this.notifyIcon1.Visible = true;
}
}
TextBoxبرای حروف بزرگ
کد:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsUpper(e.KeyChar) || char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}
ریختن مقادیر TextBoxها در DataGridView
کد:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string firstColum = textBox1.Text;
string secondColum = textBox2.Text;
string[] row = { firstColum, secondColum };
dataGridView1.Rows.Add(row);
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Columns.Add("Column1", "Column1");
this.dataGridView1.Columns.Add("Column2", "Column2");
}
}
}
دریافت لیست فایلهای کپی شده در کلیب بورد ویندوز در سی شارپ
کد:
using System.Collections.Specialized;
private void button1_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsFileDropList())
{
StringCollection file_names = Clipboard.GetFileDropList();
foreach (string file_name in file_names)
{
listBox1.Items.Add(file_name);
}
}
}
ایجاد یک نوار پیشرفت (progress bar) در محیط کنسول
کد:
using System;
using System.Text;
using System.Threading;
namespace test56
{
class ConsoleProgressBar
{
public static void Main(string[] args)
{
StringBuilder progress = new StringBuilder();
for (int i = 1; i <= 100; i++)
{
if (i % 10 == 0)
{
progress.Append("=");
}
Console.Write(i + "% " + progress.ToString() + "\r");
Thread.Sleep(100);
}
Console.Write("Done! ");
}
}
}