0

i came from a vb6 background and I'm slowly testing the c# waters. my problem is i have difficulty in adapting an object oriented approach in my programs as i tend to pattern my programs the way i use to code in vb6. take for example this data entry part of software i am creating, as you see i am still coding it the way i code in vb6.

namespace WLMS
{
public partial class frmBA : Form
{
    enum status
    {
        add,
        edit,
        delete,
        complete,
        datafill,
    }

    status stat;
    clsSqlCommands sqlCommands = new clsSqlCommands();
    string connectionString = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
    int dataID = 0;


    public frmBA()
    {
        InitializeComponent();

    }

    private void displayInGrid()
    { 
        DataTable dt = new DataTable();
        dt = sqlCommands.dataFill("select series,baName,baLoc from tblBA order by baName",connectionString);
        if (dt != null)
        {
            dgBA_List.DataSource = dt;
            dgBA_List.Columns[0].HeaderText = null;
            dgBA_List.Columns[1].HeaderText = "BA NAME";
            dgBA_List.Columns[2].HeaderText = "BA LOCATION";
            dgBA_List.Columns[0].Visible = false;
            dgBA_List.Columns[1].Width = 100;
            dgBA_List.Columns[2].Width = 200;
            dataID = 0;        
        }
    }

    private void frmBA_Load(object sender, EventArgs e)
    {
        displayInGrid();
    }

    private void tlADD_Click(object sender, EventArgs e)
    {
        groupBox1.Enabled = true;
        clearTextBoxes(groupBox1);
        txtBAName.Focus();
        stat = status.add;
    }

    private void tlEDIT_Click(object sender, EventArgs e)
    {
        if (dataID != 0)
        {
            groupBox1.Enabled = true;
            stat = status.edit;
        }
        else
            MessageBox.Show("click on item to edit");
    }


    private void tlDELETE_Click(object sender, EventArgs e)
    {
        deleteData();
    }

    private void tlSAVE_Click(object sender, EventArgs e)
    {
        if (checkFilledTextBoxes(groupBox1) == true)
        {
            switch (stat)
            {
                case status.add:
                {
                    addNewData();
                    break;
                }
                case status.edit:
                {
                    editData();
                    break;
                }
                default:
                {
                    break;
                }
            }
        }

    }

    private bool checkForDuplicates()
    {
        DataRow dtr = sqlCommands.getOneRow("select count(*) as cnt from tblba where baName = '" + txtBAName.Text + "' and baLoc = '" + txtBALoc.Text + "'", connectionString);
        if (Convert.ToInt16(dtr["cnt"]) < 1)
        {
            return false;
        }
        else
            return true;
    }

    private void editData()
    {
        if (!checkForDuplicates())
        {
            sqlCommands.dataManipulate("update tblBa set baName = '" + txtBAName.Text + "',baLoc =  '" + txtBALoc.Text + "' where series = " + dataID + "", connectionString);
            clearTextBoxes(groupBox1);
            groupBox1.Enabled = false;
            stat = status.complete;
            displayInGrid();
            MessageBox.Show("Record Edited");
        }
        else
            MessageBox.Show("Duplicate record");
    }

    private void deleteData()
    {
        DialogResult dialogResult = MessageBox.Show("Are you sure?", "", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            sqlCommands.dataManipulate("delete from tblBa where series = " + dataID + "", connectionString);
            clearTextBoxes(groupBox1);
            groupBox1.Enabled = false;
            stat = status.complete;
            displayInGrid();
            MessageBox.Show("Record deleted");
        }
        else
            MessageBox.Show("Duplicate record");
    }

    private void addNewData()
    {
        if (!checkForDuplicates())
        {
            sqlCommands.dataManipulate("insert into tblBa (baName,baLoc) values ('" + txtBAName.Text + "','" + txtBALoc.Text + "')", connectionString);
            clearTextBoxes(groupBox1);
            txtBAName.Focus();
            stat = status.complete;
            displayInGrid();

            MessageBox.Show("Record Added");
        }
        else
            MessageBox.Show("Duplicate record");
    }

    private void clearTextBoxes(GroupBox gprx)
    {
        foreach (TextBox txtBx in gprx.Controls.OfType<TextBox>())
        {
            txtBx.Text = "";
        }
    }

    private Boolean checkFilledTextBoxes(GroupBox gprx)
    {
        foreach (TextBox txtBx in gprx.Controls.OfType<TextBox>())
        {
            if (txtBx.Text == "")
                return false;
        }
        return true;
    }

    private void tlEXIT_Click(object sender, EventArgs e)
    {
        this.Dispose();
    }

    private void dgBA_List_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int rowIndex = e.RowIndex;
        DataGridViewRow row = dgBA_List.Rows[rowIndex];
        dataID = Convert.ToInt16(row.Cells[0].Value);
        txtBALoc.Text = row.Cells[1].Value.ToString();
        txtBAName.Text = row.Cells[2].Value.ToString();
        groupBox1.Enabled = false;
    }
}
}

it has two textboxes that are inside a groupbox, one datagridview and 5 toolstrip buttons to add,edit,delete,save and exit. My question is, how can i restructure my code to have an object oriented approach?

PLEASE HELP.. thanks

overmind
  • 467
  • 1
  • 8
  • 17
  • 1
    What do you actually mean by "Object oriented approach"? Do you feel you need to somehow transform your code into some beautiful abstract object shining with internal radiance because on some level, you feel the code you wrote does not appease the gods of OO? I see nothing wrong with you have written above. Despite what some people might say, VB6 *is* an object-oriented language. It just doesn't do class inheritance. Well, that's just too bad. I've seen a hell of a lot of bad code where people wrote tedious inheritance hierachies - just because they could. What are you trying to achieve? – Mark Bertenshaw Jun 17 '12 at 12:46
  • 1
    @MarkBertenshaw it never hurts to try to learn different approaches. Why the rant? Why the aggressive tone? The above is a legitimate question. – Dennis Traub Jun 17 '12 at 15:52
  • @DennisTraub thanks for having my back. actually this is my first post for stackoverflow and i was afraid that my head would be immediately placed on a stake for asking newbie questions. :) – overmind Jun 18 '12 at 04:37
  • @MarkBertenshaw, forgive me if my question is somewhat vague but you are right on your assumption. that is exactly how i feel. :) i'm afraid that im not coding the way that it should be done and im not conforming to the OO approach. actually i have no formal schooling on programming. i just practiced at home and searched wonderful forums like stackoverflow. – overmind Jun 18 '12 at 04:53
  • @DenmisTraub - Agreed - it doesn't hurt at all. Rant? - No. I was just saying that the code there was totally fine, and Overmind doesn't have to feel that he is doing anything wrong. I was making an observation that some programmers seem to think the point of OO is to make beautiful abstractions, not Get Things Done. VB6 Gets Things Done in spades. Overmind - good for you! I got into programming the same way, and have had an interesting career as a result. It is brilliant that you have the humility to ask questions like these. Just remember that some answers are somewhat subjective :-) – Mark Bertenshaw Jun 18 '12 at 13:06
  • Shouldn't this go on the [code review SE](http://codereview.stackexchange.com/)? – Deanna Jun 19 '12 at 08:44

2 Answers2

2

As you are using a GUI, I would suggest a little reading on the MVC pattern (Winforms) Looking for clean WinForms MVC tutorial for C# or MVVM pattern (WPF) MVVM: Tutorial from start to finish?.

I would also suggest reading a decent design patterns book. The one that I found quite useful when first starting was the Head First Design Patterns book. Very easy to follow. The language they use is Java, but this is very syntactically close to C#.

Maybe also have a read of this excellent Martin Fowler article on GUI architectures: http://martinfowler.com/eaaDev/uiArchs.html

Edit: Following on from Dennis' comment. You may also have a look at the MVP pattern for Winform development. A couple of different ways of implementing that pattern: http://martinfowler.com/eaaDev/SupervisingPresenter.html and http://martinfowler.com/eaaDev/PassiveScreen.html

Community
  • 1
  • 1
Steve
  • 2,950
  • 3
  • 21
  • 32
  • I'd rather prefer MVP over MVC in a Windows.Forms application. – Dennis Traub Jun 17 '12 at 12:16
  • @Dennis - i've never used MVP so cannot comment. I know that Martin Fowler has some good articles on that. I'll update my answer with those links. – Steve Jun 17 '12 at 12:17
0

Simple answer - you can not.

Depending on technology.

  • ASP.NET - use MVC, then it is natural.
  • WPF: well, UI is in XAML anyway. Winforms: you can not, control are done in the designer and data bdinding is not too good.

The best yo ucan do in WInForms is actually not holding the logic in the form but in another object, but the form is done in the way the designer wants it, or you loose all compatibility.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • Broken. THis is not about patterns, it is about (a) the way windows designers work and (b) the limited support for data binding (which was fixed in WPF). You can do a lot of things, bt none is worth loosing designer support. SAdly this is where winforms is at the moment. THings are a LOT better with WPF. – TomTom Jun 18 '12 at 09:08