通用选择窗体

做一个程序下来,为了伺候好客户老爷子,基本上是把手输的都用选择代替。因此写一个通用的选择窗体很有必要。

如下,做了个简易的窗体。

 

 

里面代码如下,没什么难的。基本的注释也有。

 

    public partial class SelectForm : Form
    {
        public string ReturnStr = "", ColumnValue = "", sql = "";
        int ColumnIndex;
        DataTable dt = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="ColumnValue">返回值的列名</param>
        public SelectForm(string sql, string ColumnValue)
        {
            this.ColumnValue = ColumnValue;
            this.sql = sql;
            InitializeComponent();
        }
        /// <summary>
        /// 页面LOAD事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectForm_Load(object sender, EventArgs e)
        {
            dataGrid.CellDoubleClick += dataGrid_CellDoubleClick;//单元格Cell双击事件
            DataBind();
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void DataBind()
        {
            dt = GetDataTable();//根据sql语句绑定数据库
            ColumnIndex = dt.Columns.IndexOf(ColumnValue);
            dataGrid.DataSource = dt;
        }
        /// <summary>
        /// 根据sql语句,返回datatable
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataTable()
        {
            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
            sb.DataSource = "liurt-pc";
            sb.InitialCatalog = "mydb";
            sb.UserID = "sa";
            sb.Password = "qaz123";
            using (SqlConnection con = new SqlConnection(sb.ToString()))
            {
                SqlDataAdapter da = new SqlDataAdapter(sql, con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }



        private void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                ReturnStr = dataGrid.Rows[e.RowIndex].Cells[ColumnIndex].Value.ToString();
                this.Close();
            }
        }

        private void txtValue_TextChanged(object sender, EventArgs e)
        {
            DataRow[] drs = dt.Select(ColumnValue + " like '%" + txtValue.Text + "%'");
            if (drs.Length == 0)
            {
                dataGrid.DataSource = null;
            }
            else
            {
                dataGrid.DataSource = drs.CopyToDataTable();
            }
        }

        private void dataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex % 2 != 0)
            { e.CellStyle.BackColor = Color.GreenYellow; } 
            else 
            { e.CellStyle.BackColor = Color.MintCream; }
        }

    }

 基本思路就是这样。

posted @ 2014-10-27 18:43  code_dream  阅读(276)  评论(0编辑  收藏  举报