DataTable search keyword

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.Security;
using System.Reflection; 
using System.Security.Permissions;

[assembly: AssemblyKeyFile("keys.snk")]
[assembly: AssemblyVersion("1.1.1.0")]
namespace FindDataTableDeme
{
    [PublisherIdentityPermission(SecurityAction.InheritanceDemand,CertFile="Certificate.cer")]
    public partial class Form1 : Form
    {
        DataSet ds = new DataSet();
        private DataRow rowFound;
        //System.Runtime.Serialization.ISerializable
        //System.SerializableAttribute

        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 塗聚文  締友計算機信息技術有限公司 Geovin Du
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //DataTable dt = findDatatble();
            //DataRow foundRow =dt.DefaultView.Find(this.textBox1.Text.Trim());
            findDatatble();
        }

        private void findDatatble()
        {

            DataTable table1 = new DataTable("table one");
            DataTable table2 = new DataTable("table two");

            //creating columns for the tables:
            table1.Columns.Add(new DataColumn("id", typeof(int)));
            table1.Columns.Add(new DataColumn("someText", typeof(string)));

            table2.Columns.Add(new DataColumn("id2", typeof(int)));
            table2.Columns.Add(new DataColumn("someOtherText", typeof(string)));

            //populating tables, one by one and add them to dataSet:
            //populating table 1:
            DataRow dr;
            for (int i = 1; i < 13; i++)
            {
                dr = table1.NewRow();
                dr["id"] = i;
                dr["someText"] = "text with number " + i.ToString();
                table1.Rows.Add(dr);
            }
            dr = table1.NewRow();
            dr["id"] = 14;
            dr["someText"] = "涂聚文";
            table1.Rows.Add(dr);
            //populating table 2:
            for (int i = 101; i < 113; i++)
            {
                dr = table2.NewRow();
                dr["id2"] = i;
                dr["someOtherText"] = "other text with number " + i.ToString();
                table2.Rows.Add(dr);
            }
            dr = table2.NewRow();
            dr["id2"] = 114;
            dr["someOtherText"] = "涂聚文";
            table2.Rows.Add(dr);
            //adding both tables to dataSet:
            ds.Tables.AddRange(new DataTable[] { table1, table2 });
            //you could add them seperately, like:
            //ds.Tables.Add(table1);
            //ds.Tables.Add(table2);
            
            
            //Now lets loop through the dataSet and write the results out (int messageBox):
            for (int i = 0; i < ds.Tables.Count; i++)      //LOOP THROUGH TABLES OF DATASET
            {
                string text = null;
                foreach (DataRow dr1 in ds.Tables[i].Rows) //LOOP TRGOUGH THE ROWS OF <strong class="highlight">DATATABLE</strong>
                {
                    string a = dr1[0].ToString();
                    string b = dr1[1].ToString();
                    text += a + ". " + b + Environment.NewLine;
                }
               // MessageBox.Show("In dataSet is dataTable of index [" + i + "] with values:\n" + text);
            }
            ds.Tables[0].DefaultView.Sort = "id";
            // Set Primary Key and Sort Order
            DataColumn[] dcolPk = new DataColumn[1];
            dcolPk[0] = ds.Tables[0].Columns["someText"];
            ds.Tables[0].PrimaryKey = dcolPk;

            dataGridView1.DataSource = ds.Tables[0].DefaultView;
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int intRow;
                object s = textBox1.Text.Trim();
                // At least one row matches primary key
                rowFound = ds.Tables[0].Rows.Find(s); //所搜索的内容,也是设定的主键
                if (rowFound != null)
                {
                    MessageBox.Show(rowFound[0].ToString()+","+rowFound[1].ToString());
                }
                else
                {
                    MessageBox.Show("A row with the primary key of " + s + " could not be found");
                }
                DataRow[] foundRows;
                foundRows = ds.Tables[0].Select("someText Like '涂%'");
                if (foundRows != null)
                {
                    MessageBox.Show(foundRows[0].ToString());
                }

                 Finds the row specified in txtFindArg
                //intRow = ds.Tables[0].DefaultView.Find(s);
                Debug.WriteLine(intRow);
                //if (intRow == -1)
                //{
                //    MessageBox.Show("No PK matches " + textBox1.Text);
                //}
                //else
                //{
                //    // Jump to the Row and select it
                //    //dataGridView1.CurrentRow.Index = intRow;  //CurrentRowIndex
                //    dataGridView1.Rows[intRow].Selected=true;
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void s()
        {
                      
            //create a datatable object which will host the two column: notebookID, notebook producer 
            DataTable o_aTable = new DataTable("Notebooks");
            

            //creating a datacolumn 
                //definition and initilization of column
                DataColumn o_aColumn = new DataColumn();
                //defining column properties
                    //caption 
                    o_aColumn.Caption = "Notebook Producers";
                    //type of column
                    o_aColumn.DataType = System.Type.GetType("System.String");
                    //access name of column 
                    o_aColumn.ColumnName = "Producer";
                    //default value
                    o_aColumn.DefaultValue = "unknown producer";

            //add column to the table
            o_aTable.Columns.Add(o_aColumn);

                //initialize a new instance of data column for creating a new column
                o_aColumn = new DataColumn();
                //defining column properties
                    //caption 
                    o_aColumn.Caption = "Notebook Producer ID";
                    //type of column
                    o_aColumn.DataType = System.Type.GetType("System.Int32");
                    //access name of column 
                    o_aColumn.ColumnName = "ProducerID";
                    //default value
                    o_aColumn.DefaultValue = 0000;

            //add new column to the table 
            o_aTable.Columns.Add(o_aColumn);

            //create a primary key column to use search
                //definition and initial.
                DataColumn[] o_aPrimaryKeyColumn = new DataColumn[1];
                //assigning notebookID column of created table to this column: it will serve as primary key column
                o_aPrimaryKeyColumn[0] = o_aTable.Columns["ProducerID"];
                //mapping primary key column of table to the created primary key holder column               
            o_aTable.PrimaryKey = o_aPrimaryKeyColumn;
            
            //adding rows-records to column
                //create a datarow object which serves as a record entry
                DataRow o_aRow;

                //adding the records
                    //add 1th record for producer HP
                        //initialize a new row for table object
                        o_aRow = o_aTable.NewRow();
                        //assign value of 1th column ID
                        o_aRow["ProducerID"] = 1;
                        //assign value of 2th column producer
                        o_aRow["Producer"] = "HP";
                        //add 1th row to the table
                        o_aTable.Rows.Add(o_aRow);

                    //add 2nd record for producer IBM
                        //initialize a new row for table object
                        o_aRow = o_aTable.NewRow();
                        //assign value of 1th column ID
                        o_aRow["ProducerID"] = 2;
                        //assign value of 2th column producer
                        o_aRow["Producer"] = "IBM";
                        //add 2nd row to the table
                        o_aTable.Rows.Add(o_aRow);

            //display the records within table

            for (int i = 0; i < o_aTable.Rows.Count;i++ )
            {
                //display ID 
                Console.WriteLine("row " + i + ": notebook ID is: " + o_aTable.Rows[i]["ProducerID"].ToString());
                //display producer
                Console.WriteLine("row " + i + ": notebook Producer is: " +  o_aTable.Rows[i]["Producer"].ToString());

            }
            //Handling row with specifying a particular primary column addressed by ID
                //create a row object to store found row which matches criteria ID
                DataRow o_dRow_findedRow;
                //look for row with id 1
                if ((o_dRow_findedRow = o_aTable.Rows.Find("1")) != null)
                {

                    Console.WriteLine("Primary key column of Table (in memory) is being queried for notebookID 1...");
                    Console.WriteLine("A row with notebookID 1 is found.");
                }
                else
                { 
                    Console.WriteLine("A record with notebookID 1 is not found.");
                }

         }

    
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值