C# 常用功能整合-2

目录

Json转为实体类,生成代码

Newtonsoft.Json中JObject的使用

分页计算 总页数、当前页数据集合

Task 定时器

事件Event

打印 DataTable 到控制台

获取 DataTable 的所有列名

DataTable 转换为实体类

单例模式 新写法

随机数

DataSet 和 DataTable 的用法

获取项目的名称

去掉字符串中的特殊字符

字符串只保留字母和数字

DataTable 基本用法


Json转为实体类,生成代码

json 如下:

{
	"Name": "Jack",
	"Age": 34,
	"Colleagues": [{
		"Name": "Tom",
		"Age": 44
	}, {
		"Name": "Abel",
		"Age": 29
	}]
}

打开网站:JSON转C#实体类-BeJSON.com

输入json,点击生成实体类就会生成实体类代码了

这里看下实体类

//如果好用,请收藏地址,帮忙分享。
public class ColleaguesItem
{
    /// <summary>
    /// 
    /// </summary>
    public string Name { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int Age { get; set; }
}
 
public class Root
{
    /// <summary>
    /// 
    /// </summary>
    public string Name { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public int Age { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public List <ColleaguesItem > Colleagues { get; set; }
}

我们用 Newtonsoft.Json 插件序列化一下,就可以将Json中的数据赋值到这个实体类中了,真的非常的方便,不过,我测试过于复杂的Json时还是有点问题的,自己手动改一下就好了

Newtonsoft.Json中JObject的使用

案例1

json

{
	"Name": "Jack",
	"Age": 34,
	"Colleagues": [{
		"Name": "Tom",
		"Age": 44
	}, {
		"Name": "Abel",
		"Age": 29
	}]
}

代码

using Newtonsoft.Json.Linq;
using System;

namespace JObject案例
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
            JObject jObject1 = JObject.Parse(json);

            string name = jObject1["Name"].ToString();
            string age = jObject1["Age"].ToString();

            string colleagues1_name = jObject1["Colleagues"][0]["Name"].ToString();
            string colleagues1_age = jObject1["Colleagues"][0]["Age"].ToString();

            Console.WriteLine(name);
            Console.WriteLine(age);
            Console.WriteLine(colleagues1_name);
            Console.WriteLine(colleagues1_age);

            Console.ReadKey();
        }
    }
}

运行

案例2

json

{
	"ID": 1,
	"Name": "张三",
	"Favorites": ["吃饭", "睡觉"]
}

代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace JObject案例
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"ID\":1,\"Name\":\"张三\",\"Favorites\":[\"吃饭\",\"睡觉\"]}";
            JObject jObject1 = JObject.Parse(json);

            Console.WriteLine(jObject1["ID"]);
            Console.WriteLine(jObject1["Name"]);
            Console.WriteLine(jObject1["Favorites"][0]);
            Console.WriteLine(jObject1["Favorites"][1]);

            Console.ReadKey();
        }
    }
}

运行

案例3

json

{
	"input": {
		"size": 193156,
		"type": "image/png"
	},
	"output": {
		"size": 59646,
		"type": "image/png",
		"width": 487,
		"height": 284,
		"ratio": 0.3088,
		"url": "https://www.baidu.com"
	}
}

代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;

namespace JObject案例
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"input\":{\"size\":193156,\"type\":\"image/png\"},\"output\":{\"size\":59646,\"type\":\"image/png\",\"width\":487,\"height\":284,\"ratio\":0.3088,\"url\":\"https://www.baidu.com\"}}";
            JObject jObject1 = JObject.Parse(json);

            Console.WriteLine(jObject1["input"]["size"]);
            Console.WriteLine(jObject1["input"]["type"]);
            Console.WriteLine(jObject1["output"]["size"]);
            Console.WriteLine(jObject1["output"]["type"]);

            Console.ReadKey();
        }
    }
}

运行

案例4 

json

{
	"code": "SUCCESS",
	"msg": null,
	"data": [{
		"id": 31783735,
		"residentInfoId": 2000099151,
		"doctorId": "89bd0716-f916-4e51-93f7-4d416830f03c"
	}]
}

代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;

namespace JObject案例
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"code\":\"SUCCESS\",\"msg\":null,\"data\":[{\"id\":31783735,\"residentInfoId\":2000099151,\"doctorId\":\"89bd0716-f916-4e51-93f7-4d416830f03c\"}]}";
            JObject jObject1 = JObject.Parse(json);

            Console.WriteLine(jObject1["code"]);
            Console.WriteLine(jObject1["SUCCESS"]);
            Console.WriteLine(jObject1["data"][0]["id"]);
            Console.WriteLine(jObject1["data"][0]["residentInfoId"]);
            Console.WriteLine(jObject1["data"][0]["doctorId"]);

            Console.ReadKey();
        }
    }
}

运行

分页计算 总页数、当前页数据集合

 代码:

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

namespace Test4
{
    class Program
    {
        static void Main(string[] args)
        {
            int AllCount = 9;
            Console.WriteLine("总个数:" + AllCount);

            int page = AllCount / PageCount;
            int remainder = AllCount % PageCount;
            Console.WriteLine("页数:" + page);
            Console.WriteLine("余数:" + remainder);

            int totalPage = remainder > 0 ? page + 1 : page;
            Console.WriteLine("总页数:" + totalPage);

            //获取第二页索引的起点和结束点
            int index = 2;
            Console.WriteLine(string.Format("获取第{0}页数据",index));
            int start = (index * PageCount) - PageCount;
            int end = (index * PageCount) - 1;
            Console.WriteLine(string.Format("起点:{0},结束点:{1},index:{2}", start, end, index));
            Console.WriteLine("========================================");


            //添加随机数
            Random random = new Random();
            for (int i = 0; i < 17; i++)
            {
                MyList.Add(random.Next(10, 1000).ToString());
            }
            Print(MyList);

            //获取当页数据集合
            Console.WriteLine("获取第3页数据");
            List<string> myList = GetIndexList(3);
            Print(myList);

            Console.ReadKey();
        }

        public static List<string> MyList = new List<string>();
        //一页的个数
        public static int PageCount = 8;

        /// <summary>
        /// 获取当页的数据集合
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static List<string> GetIndexList(int index)
        {
            if (MyList.Count <= 0) return null;
            
            int page = MyList.Count / PageCount;
            int remainder = MyList.Count % PageCount;
            int allPage = remainder > 0 ? page + 1 : page;

            if (index > allPage) return null;

            int start = (index * PageCount) - PageCount;
            int end = (index * PageCount) - 1;
            if (end > MyList.Count) end = MyList.Count -1;

            List<string> list = new List<string>();
            for (int i = start; i <= end; i++)
            {
                list.Add(MyList[i]);
            }

            if(list.Count > 0)
                return list;
            return null;
        }

        public static void Print(List<string> list)
        {
            if (list == null || list.Count <= 0) return;

            string msg = string.Empty;
            for (int i = 0; i < list.Count; i++)
            {
                msg += list[i] + ",";
            }

            Console.WriteLine(msg);
        }
    }
}

输出结果:

总个数:9
页数:1
余数:1
总页数:2
获取第2页数据
起点:8,结束点:15,index:2
====
393,318,19,71,597,684,59,892,134,773,657,32,264,231,296,257,733,
获取第3页数据
733,
 

注意===线下面的数据是随机数,每次运行结果不一样,

获取的是第3页,而当前总个数是17,一页是8个,第3页刚好是最后一个,可以看到,计算没有问题

Task 定时器

使用C#的定时器,在使用多线程时会出现,回调方法不执行的情况,用Task作为定时器也是个不错的选择。

异步延时执行代码:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Task延时执行
{
    class Program
    {
        static void Main(string[] args)
        {
            //调用方法1
            Task.Factory.StartNew(TimerTask);
            Thread.Sleep(2000);
            //调用方法2 这里也可以使用Lambda表达式
            Task.Run(TimerTask);

            Console.ReadKey();
        }

        private static async Task TimerTask()
        {
            //异步方式等待2秒
            await Task.Delay(TimeSpan.FromSeconds(2));
            Console.WriteLine("等待2秒");
        }
    }
}

假设需要一个定时器,循环的执行,看下面代码

代码:

using System;
using System.Threading.Tasks;

namespace Task循环执行
{
    class Program
    {
        private static bool isStop = false;
        private static int index = 0;

        static void Main(string[] args)
        {
            isStop = true;
            Task.Run(DosomeThingAsync);
            Console.ReadKey();
        }

        private static async Task DosomeThingAsync()
        {
            while (isStop)
            {
                await Task.Delay(TimeSpan.FromSeconds(2));
                index++;
                Console.WriteLine("index:"+index);
                if(index >= 5)
                {
                    isStop = false;//退出循环
                    index = 0;
                }
            }
        }
    }
}

运行:

事件Event

代码

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

namespace Events
{
    public class Bridegroom
    {
        //自定义委托
        public delegate void MarryHandler(string msg);
        //使用自定义委托定义事件,事件名MarryEvent
        public event MarryHandler MarryEvent;
        public void onMarriageComing(string msg)
        {
            if(MarryEvent != null)
            {
                //触发事件
                MarryEvent(msg);
            }
        }
    }

    public class Friend
    {
        public string Name;
        public Friend(string name)
        {
            Name = name;
        }

        public void SendMessage(string mess)
        {
            //处理事件
            Console.WriteLine(this.Name + "收到了,到时候准时参加!");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Bridegroom bridegroom = new Bridegroom();
            Friend friend1 = new Friend("张三");
            Friend friend2 = new Friend("李四");
            Friend friend3 = new Friend("王五");

            bridegroom.MarryEvent += new Bridegroom.MarryHandler(friend1.SendMessage);
            bridegroom.MarryEvent += new Bridegroom.MarryHandler(friend2.SendMessage);

            bridegroom.onMarriageComing("朋友们,结婚了");

            Console.ReadKey();
        }
    }
}

打印 DataTable 到控制台

代码:

//打印所有列名
string columnName = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
    //columnName += dataTable.Columns[i].ColumnName + " | ";
    columnName += string.Format("{0}({1}) | ", dataTable.Columns[i].ColumnName, i);
}
Console.WriteLine(columnName);

//打印每一行的数据
foreach (DataRow row in dataTable.Rows)
{
    string columnStr = string.Empty;
    foreach (DataColumn column in dataTable.Columns)
    {
        columnStr += row[column] + " | ";
    }
    Console.WriteLine(columnStr);
}

对于 打印每一行的数据,如果你不想用 foreach 循环,还可以使用下面写法,效果一样的

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    string columnStr = string.Empty;
    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        columnStr += dataTable.Rows[i][j] + " | ";
    }
    Console.WriteLine(columnStr);
}

获取 DataTable 的所有列名

代码:


private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataTable dt = new DataTable("Datas");
    DataColumn dc = new DataColumn();
    dc.AutoIncrement = true;//自动增加
    dc.AutoIncrementSeed = 1;//起始为1
    dc.AutoIncrementStep = 1;//步长为1
    dc.AllowDBNull = false;//是否允许空值

    //添加列
    dc = dt.Columns.Add("ID", Type.GetType("System.String"));
    dc = dt.Columns.Add("Product", Type.GetType("System.String"));
    dc = dt.Columns.Add("Version", Type.GetType("System.String"));
    dc = dt.Columns.Add("Description", Type.GetType("System.String"));

    if (dt.Columns.Count > 0)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            Console.WriteLine("列名:" + dt.Columns[i].ColumnName);
        }
    }  
}

运行:

DataTable 转换为实体类

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;

/// <summary>
/// 将DataTable数据源转换成实体类
/// </summary>
public static class ConvertTool
{
    /// <summary>
    /// DataTable转换成实体类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<T> TableToEntity<T>(DataTable dt) where T : class, new()
    {
        List<T> list = new List<T>();
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                T entity = new T();
                PropertyInfo[] pArray = entity.GetType().GetProperties();

                foreach (PropertyInfo p in pArray)
                {
                    if (dt.Columns.Contains(p.Name))
                    {
                        if (!p.CanWrite) continue;
                        var value = row[p.Name];
                        if (value != DBNull.Value)
                        {
                            Type targetType = p.PropertyType;
                            Type convertType = targetType;
                            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                            {
                                //可空类型
                                NullableConverter nullableConverter = new NullableConverter(targetType);
                                convertType = nullableConverter.UnderlyingType;
                            }
                            if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value.ToString()))
                            {
                                value = Convert.ChangeType(value, convertType);
                            }
                            switch (convertType.FullName)
                            {
                                case "System.Decimal":
                                    p.SetValue(entity, Convert.ToDecimal(value), null);
                                    break;
                                case "System.String":
                                    p.SetValue(entity, Convert.ToString(value), null);
                                    break;
                                case "System.Int32":
                                    p.SetValue(entity, Convert.ToInt32(value), null);
                                    break;
                                case "System.Int64":
                                    p.SetValue(entity, Convert.ToInt64(value), null);
                                    break;
                                case "System.Int16":
                                    p.SetValue(entity, Convert.ToInt16(value), null);
                                    break;
                                case "System.Double":
                                    p.SetValue(entity, Convert.ToDouble(value), null);
                                    break;
                                case "System.DateTime":
                                    p.SetValue(entity, Convert.ToDateTime(value), null);
                                    break;
                                default:
                                    p.SetValue(entity, value, null);
                                    break;
                            }
                        }
                    }
                }
                list.Add(entity);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        if(list.Count > 0)
            return list;
        else
            return null;
    }

}

单例模式 新写法

传统写法,适用于Winform,控制台,在Unity3d里面不太合适这种方式。

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

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test.Instance.SayHi();

            Console.ReadKey();  
        }
    }


    public class Test
    {
        private static Test instance;
        public static Test Instance
        {
            get
            {
                if (instance == null)
                    instance = new Test();
                return instance;
            }
        }

        public void SayHi()
        {
            Console.WriteLine("oh my god");
        }

        private Test()
        {
            
        }
    }
}

新写法:

新写法和传统写法比起来要少写一些代码,效果是一样的

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

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test.Instance.SayHi();

            Console.ReadKey();  
        }
    }


    public class Test
    {
        public static Test Instance;

        public void SayHi()
        {
            Console.WriteLine("oh my god");
        }

        private Test()
        {
            
        }

        static Test()
        {
            Instance = new Test();
        }
    }
}

随机数

随机整数和随机小数

public class RandomNum
{
    /// <summary>
    /// 获取随机整数
    /// </summary>
    /// <param name="count">你需要几个随机数</param>
    /// <param name="minNum">下限</param>
    /// <param name="maxNum">上限</param>
    /// <returns>返回随机数的数组,长度根据个数而定</returns>
    public static int[] GetRandomArray(int count, int minNum, int maxNum)
    {
        int[] randomArr = new int[count];
        Random r = new Random();
        for (int j = 0; j < count; j++)
        {
            int i = r.Next(minNum, maxNum + 1);
            int num = 0;
            for (int k = 0; k < j; k++)
            {
                if (randomArr[k] == i) num = num + 1;
            }
            if (num == 0)
                randomArr[j] = i;
            else
                j = j - 1;
        }
        return randomArr;
    }

    /// <summary>
    /// 获取随机浮点数
    /// </summary>
    /// <param name="minimum">下限</param>
    /// <param name="maximum">上限</param>
    /// <param name="Len">小数点保留位数</param>
    /// <returns>随机的浮点数</returns>
    public static double GetRandomNumber(double minimum, double maximum, int Len)
    {
        Random random = new Random();
        //注意:不用间隔时间,使用for循环获取,返回的几个随机数会一模一样
        System.Threading.Thread.Sleep(1);
        return Math.Round(random.NextDouble() * (maximum - minimum) + minimum, Len);
    }
}

DataSet 和 DataTable 的用法

代码:


//DataSet 的 Table 可以装多个表单(DataTable)
DataSet ds = new DataSet();
//创建一个表单
DataTable dt = new DataTable("Name");

//添加列
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Sex", typeof(string)));
dt.Columns.Add(new DataColumn("Addr", typeof(string)));

//添加一行数据到列中
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["Name"] = "张三";
dr["Sex"] = "不男不女";
dr["addr"] = "泰国";

//添加一行数据到表单中
dt.Rows.Add(dr);

//将表单添加到DataSet的表单列表中
ds.Tables.Add(dt);

//显示到界面中
//dataGridView1.DataSource = ds.Tables[0];
//和上行代码效果一样
dataGridView1.DataSource = dt;

效果:

获取项目的名称

一、控制台

通过 Assembly.GetEntryAssembly().GetName() 可以得到项目名称,版本号等信息,如下:

ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

获取项目名称:

代码:

Console.WriteLine(Assembly.GetEntryAssembly().GetName().Name);

输出:

ConsoleApp1

二、Windows Form

Application.ProductName

去掉字符串中的特殊字符

方案一:

string except_chars = ": ‘ ! @ # % … & * (  ^  &  ¥  , 。 , .)$";
string src = "就是包含: 这些‘字符 包含空格)都要$去掉么?";
string result = Regex.Replace(src, "[" + Regex.Escape(except_chars) + "]", "");

方案二:

//只保留字母、数字 和汉字
string strAfter= Regex.Replace(strBefor, @"[^a-zA-Z0-9\u4e00-\u9fa5\s]", "");

字符串只保留字母和数字

代码:

public static string GetNumberAlpha(string source)
{
    string pattern = "[A-Za-z0-9]";
    string strRet = "";
    MatchCollection results = Regex.Matches(source, pattern);
    foreach (var v in results)
    {
        strRet += v.ToString();
    }
    return strRet;
}

DataTable 基本用法

创建一个窗体程序:

添加两个组件:

1.组件名:dataGridView1

给组件添加要给自动排序的方法,在CellPainting双击

2.button

双击自动添加点击事件

全部代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LJYZN_105
{
    public partial class Form3 : Form
    {

        DataTable dt = null;

        public Form3()
        {
            InitializeComponent();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            Table();
        }

        private void Table()
        {
            //DataTable dt = new DataTable("Datas");
            //DataColumn dc1 = new DataColumn("商品编号");
            //DataColumn dc2 = new DataColumn("商品名称");
            //DataColumn dc3 = new DataColumn("商品重量");
            //DataColumn dc4 = new DataColumn("商品价格");
            //DataColumn dc5 = new DataColumn("购买数量");
            //dt.Columns.Add(dc1);
            //dt.Columns.Add(dc2);
            //dt.Columns.Add(dc3);
            //dt.Columns.Add(dc4);
            //dt.Columns.Add(dc5);

            dt = new DataTable("Datas");
            DataColumn dc = new DataColumn();
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;//是否允许空值

            //添加列
            dc = dt.Columns.Add("ID", Type.GetType("System.String"));
            dc = dt.Columns.Add("Product", Type.GetType("System.String"));
            dc = dt.Columns.Add("Version", Type.GetType("System.String"));
            dc = dt.Columns.Add("Description", Type.GetType("System.String"));

            DataRow newRow;
            //第一种方式
            newRow = dt.NewRow();
            newRow["ID"] = "1";
            newRow["Product"] = "南瓜";
            newRow["Version"] = "2.0";
            newRow["Description"] = "熟了";
            dt.Rows.Add(newRow);

            newRow = dt.NewRow();
            newRow["ID"] = "2";
            newRow["Product"] = "西瓜";
            newRow["Version"] = "3.0";
            newRow["Description"] = "熟了";
            dt.Rows.Add(newRow);

            //第二种方式
            dt.Rows.Add(new object[] {"3", "冬瓜", "4.0", "没熟" });

            //绑定数据
            this.dataGridView1.DataSource = dt;
            //设置列的宽度
            this.dataGridView1.Columns[0].Width = 50;

            //查找是否存在某个值
            bool res = IsIncludeData(dt, "Product", "西瓜");
            Console.WriteLine("===========查找结果:" + res);

            //查找在那一行
            dt.PrimaryKey = new System.Data.DataColumn[] { dt.Columns["Product"] };
            DataRow dataRow = dt.Rows.Find("南瓜");
            if (dataRow != null)
            {
                Console.WriteLine("===========查找列并获取版本:" + dataRow["Version"]);
                //将查到的值重新赋值
                dataRow["Version"] = 100;
                //删除南瓜这行
                dt.Rows.Remove(dataRow);
            }

            //DataTable dt = new DataTable();
            //dt.Rows[i];//已知
            //dt.Rows[--i];//上一行
            //dt.Rows[++i];//下一行

            //获取这一列是那一行
            int rowNum = FindRowIndex(dataRow);
            Console.WriteLine("===========行号:" + rowNum);
        }


        /// <summary>
        /// 设置DataGridView组件的列序号自动增加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex < 0 && e.RowIndex >= 0) // 绘制 自动序号
            {
                e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
                Rectangle vRect = e.CellBounds;
                vRect.Inflate(-2, 2);
                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), e.CellStyle.Font, vRect, e.CellStyle.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
                e.Handled = true;
            }
            // ----- 其它样式设置 -------
            if (e.RowIndex % 2 == 0)
            { // 行序号为双数(含0)时 
                e.CellStyle.BackColor = Color.White;
            }
            else
            {
                e.CellStyle.BackColor = Color.Honeydew;
            }
            e.CellStyle.SelectionBackColor = Color.Gray; // 选中单元格时,背景色
            e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //单位格内数据对齐方式
        }

        /// <summary>
        /// 判断DataTable中的列是否存在某个值
        /// </summary>
        /// <param name="dt">DataTable类</param>
        /// <param name="columnName">列名</param>
        /// <param name="fieldData">要查找的值字符串</param>
        /// <returns>包含这个值返回true,不包含返回false</returns>
        public bool IsIncludeData(DataTable dt, String columnName, string fieldData)
        {
            if (dt == null)
            {
                return false;
            }
            else
            {
                if (dt.Select(columnName + "='" + fieldData + "'").Length > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 获取行号
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private int FindRowIndex(DataRow dr)
        {
            return dr.Table.Rows.IndexOf(dr);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dt.Rows.Add(new object[] { "茄子", "5.0", "半熟" });
        }
    }
}

运行:

图中的100是通过查找获取到行(DataRow),并修改它的值

下面的按钮,可以随时向DataGridView内添加数据,自动放到表格的最下面一行

这里我们只需要改dt内数据,就可以随时显示最新的数据了

end

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊思宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值