c#初学者对课堂问题感到沮丧

时间:2010-11-05 20:23:07

标签: c# .net winforms class

我创建了一个winforms应用程序。它的作用是查询数据库并在屏幕上的图表上显示数据。

我的问题是,为此使用类是否合适?我知道答案可能是肯定的,但我不知道如何使用这个类。

这是我的代码。如果您认为这是正确的做法,请给我一些关于如何将其变成课程的建议:

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.Windows.Forms.DataVisualization.Charting;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private DataTable qResults = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
        {
           string qcvalues_query = "SELECT DISTINCT name FROM qvalues ORDER by name";
           string analytes_query = "SELECT DISTINCT compound FROM qvalues ORDER by compound";
           string instruments_query = "SELECT DISTINCT instrument FROM batchinfo WHERE instrument <> '' AND instrument is not Null ORDER by instrument";

           dataGridView1.MultiSelect = false;

           cbAnalytes.DisplayMember = "name";
           cbAnalytes.DataSource = ConnectandReadList(qcvalues_query);

           cbQCValues.DisplayMember = "compound";
           cbQCValues.DataSource = ConnectandReadList(analytes_query);

           cbInstruments.DisplayMember = "instrument";
           cbInstruments.DataSource = ConnectandReadList(instruments_query);
        }
        private DataSet GetSeriesValues()
        {

            Series ser = this.chart1.Series["Series1"];

            DataSet dataSet = new DataSet();
            DataTable seriesTable = new DataTable(ser.Name);

            seriesTable.Columns.Add(new DataColumn("No", typeof(int)));
            seriesTable.Columns.Add(new DataColumn("X", typeof(string)));
            seriesTable.Columns.Add(new DataColumn("Y", typeof(double)));

            for (int count = 0; count < ser.Points.Count; count++)
            {
                DataPoint p = ser.Points[count];
                seriesTable.Rows.Add(new object[] { count, p.XValue, p.YValues[0] });
            }

            dataSet.Tables.Add(seriesTable);
            return dataSet;
        }

        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            // Call Hit Test Method
            HitTestResult result = chart1.HitTest(e.X, e.Y);

            // Reset Data Point Attributes
            foreach (DataPoint point in chart1.Series[0].Points)
            {
                point.BackSecondaryColor = Color.Black;
                point.BackHatchStyle = ChartHatchStyle.None;
                point.BorderWidth = 1;
            }

            // If a Data Point or a Legend item is selected.
            if
            (result.ChartElementType == ChartElementType.DataPoint ||
                result.ChartElementType == ChartElementType.LegendItem)

                {
                    try
                    {
                        // Set cursor type 
                        this.Cursor = Cursors.Hand;


                        // Find selected data point
                        DataPoint point = chart1.Series[0].Points[result.PointIndex];

                        // Set End Gradient Color to White
                        point.BackSecondaryColor = Color.White;

                        // Set selected hatch style
                        point.BackHatchStyle = ChartHatchStyle.Percent25;

                        // Increase border width
                        point.BorderWidth = 2;
                    }
                    catch { }
                }
            else
            {
                // Set default cursor
                this.Cursor = Cursors.Default;
            }
        }


        private void InitializeChart()
        {
            chart1.Series["Series1"].ChartType = SeriesChartType.Line;
            chart1.Series["Series1"].MarkerStyle = MarkerStyle.Circle;
            chart1.Series["Series1"].MarkerSize = 8;

            // Set series members names for the X and Y values
            chart1.Series["Series1"].XValueMember = "datapath";
            chart1.Series["Series1"].YValueMembers = "finalconc";



            chart1.DataBind();

            // Calculate Mean
            double mean = chart1.DataManipulator.Statistics.Mean("Series1");

            // Calculate Median
            double median = chart1.DataManipulator.Statistics.Median("Series1");

            // Calculate Standard Deviation from the Variance
            double variance = chart1.DataManipulator.Statistics.Variance("Series1", true);
            double standardDeviation = Math.Sqrt(variance);

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[0].IntervalOffset = mean - Math.Sqrt(variance);
            chart1.ChartAreas[0].AxisY.StripLines[0].StripWidth = 2.0 * Math.Sqrt(variance);

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[1].IntervalOffset = mean;

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[2].IntervalOffset = median;

            DataPoint maxValuePoint = chart1.Series["Series1"].Points.FindMaxByValue();
            DataPoint minValuePoint = chart1.Series["Series1"].Points.FindMinByValue();

            chart1.ChartAreas[0].AxisY.Maximum = maxValuePoint.YValues.Max();
            chart1.ChartAreas[0].AxisY.Minimum = minValuePoint.YValues.Min();

            // Refresh Chart
            chart1.Invalidate();

        }

        private DataTable ConnectandReadList(string query)
        {
            DataTable ds = new DataTable();
            string connection_string = "Data Source=hermes;database=qcvalues; Integrated Security=SSPI;";
            using (var myConnection = new SqlConnection(connection_string))
            {
                myConnection.Open();
                var command = new SqlCommand(query, myConnection);
                var adapter = new SqlDataAdapter(command);
                adapter.Fill(ds);
            }
            return ds;
        }


        private void btnGenerateGraph_Click(object sender, EventArgs e)
        {
            string graph_query = @"SELECT top 1000 reporttime,
                    datapath,
                    finalconc, 
                    instrument 
                    FROM batchinfo  
                    JOIN qvalues ON batchinfo.rowid = qvalues.rowid
                    WHERE compound = '" + cbQCValues.Text + "'" +
                    "AND name = '" + cbAnalytes.Text + "'" +
                    "AND batchinfo.instrument = '" + cbInstruments.Text + "'" +
                    "AND batchinfo.reporttime LIKE '10/%/2010%'";


            qResults = ConnectandReadList(graph_query);
            if (qResults.Rows.Count == 0)
            {
                MessageBox.Show("Your query did not return any results!");
                return;
            }

            chart1.DataSource = qResults;
            InitializeChart();


            dataGridView1.Columns.Clear();
            dataGridView1.DataBindings.Clear();
            dataGridView1.DataSource = qResults;

        }

        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            // Call Hit Test Method
            HitTestResult result = chart1.HitTest(e.X, e.Y);

            if (result.ChartElementType == ChartElementType.DataPoint)
            {

                dataGridView1.Rows[result.PointIndex].Selected = true;
                dataGridView1.FirstDisplayedScrollingRowIndex = result.PointIndex;

            }


        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Int32 selectedRowCount =
        dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount == 1)
            {                                   
                qResults.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                InitializeChart();                          

            }
        }


    }
}

4 个答案:

答案 0 :(得分:2)

如何组织代码取决于应用程序的规模和复杂程度。

如果您正在编写大型应用程序,则可能需要使用不同的层来处理数据库,业务逻辑和表示。

对于像您这样的小型应用程序,将数据绑定直接用于数据库查询可能更简单。

答案 1 :(得分:2)

您已经在使用类,但不是最干净,最模块化的方法。将数据操作和业务逻辑组合在一个UI类中通常被认为是一个坏主意。这就是发明MVC composite pattern的原因,将您的数据,用户界面和商业逻辑分成更多模块化的部分。

Here's another article,C#特定,可以查看。

答案 2 :(得分:2)

我认为这是一个主观问题......如果它已经有效,为什么还要修复它?

但是从另一个角度来看,如果这是一个更大的系统的一部分,我会把它拆分成不同的类,而是分开的程序集和命名空间。

对于手头的任务,您的代码是正确的。我现在不担心,除非你已经是一名熟练的程序员(了解语法),目标是为更大规模的系统实现良好的模块化系统设计。

答案 3 :(得分:1)

我对此表示不满。 Form1是一个类。

此时我可能建议的唯一真正的改变是将其变成复合控制。这样,您可以根据需要将该功能放到不同的表单上。

查看MS walkthroughsmaller article here

除了学习新东西之外别无他法,你可能会这样做。