Hi EveryOne,

Can I ask your help/suggestion:

click a button to open popup window, how can i carry the one of col. info to parent window's text box when user double click the row in listview in popup window.

I have a code collected in the online for PopUpform:

 private void srchbtn_Click(object sender, EventArgs e)
        {
            searchmember popup = new searchmember();
            DialogResult dialogresult = popup.ShowDialog();
            if (dialogresult == DialogResult.OK)
            {
                Console.WriteLine("You clicked OK");
            }
            else if (dialogresult == DialogResult.Cancel)
            {
                Console.WriteLine("You clicked either Cancel or X button in the top right corner");
            }
            popup.Dispose();
        }

I have also a Double Click in DataGridView code popup:

  1. You have ParenForm from where you want to show the popup. It has SomeTextBox which you want to fill with text from popupform.

  2. You have PopupForm where your DataGridView is present.

  3. Add new Property in the PopupForm eg. SomeProperty

  4. In the ParentForm in some button click event write something like this to load popup form:

    PopupForm form1 = new PopupForm();

    if(form1.ShowDialog()==DialogResult.OK) // popup form is loaded here and parent form will wait for dialogresult from popup window.

    {

    this.SomeTextBox.Text = form1.SomeProperty;

    }

  5. In the doubleclick event of datagridview row :

    this.SomeProperty = "somevalue";

    this.DialogResult = DialogResult.OK;

However, My point to post this query in this forum, is I want to know, How to code this in ListView? I'm Using MySQL;

[IMG]http://i61.tinypic.com/2lvy5vd.jpg[/IMG]

[IMG]http://i58.tinypic.com/2e6bfp0.png[/IMG]

regrads,
Darryl

Edited 2 Years Ago by darrylnuyda: add content

Attachments Screenshot_2.png 33.44 KB Screenshot_1.png 16.71 KB

You would most likely use logic along the following lines.

  1. Have a public facing property on the pop-up form.
  2. When a row is chosen on the pop-up form, set the property to the details of the row (briefly discussed below).
  3. Back in the main form, during the if check for the ok response from the pop-up, if it is true, you retrieve the values onto the main form through the exposed property.

If you wanted all the values from the selected row I guess you would need to put them into a string and .Split() it the other end, or use an array/list to store the multiple values.

In terms of how to do it using a list view, you could make use of the SelectedIndexChanged event to update the property.

Else please elaborate further if I have not understood :)

I hope I didn't misunderstand your question:

So let's say you have 2 forms, Form1, and Form2. Your main form is Form1, your popup form is Form2. You also have 1 textbox and one button on each of the forms, but when you click on the button from the Form1, you'll get the popup Form2, and when you click on the button from the Form2, you'll return to Form1, and whatever you wrote in the textbox from Form2 will be display in Form1.

Form1:

private void button1_Click(object sender, EventArgs e)
{
    this.Hide();
    var obj = new Form2();
    obj.ShowDialog();
    this.Show();
    textBox1.Text = obj.textbox;
}

Form2:

public string textbox = "";
private void button1_Click(object sender, EventArgs e)
{
    textbox = textBox1.Text;
    this.Close();
}

So, you have a variable in your popup form that will hold the information, and whenever you want to send back those information, you just set the variable to those, and access it in the main form. After that, you can dispose of the popup form.

@lucaci Andrew: Thank you for your reply, I think you understand my question about the popup form(form1 to form2, and Form2 to form1), How about in ListView in Form2, if I entered a data in textbox is viewing to the listView, after that I double click the ListView then the data will transfer to form 1.

regards,

Darryl

To use MySql database with .Net you need to install ADO.Net Driver For MySql, you can get it from mysql.com

Actually there are various ways to populate your database table into a ListView and retreive its value, you can either use database binding technique or simply use DataReader to read the entire query result then fill it into your ListView

Here is an example :

First, add some columns you need in your ListView by using Form Designer, this example using two columns

public void LoadData()
{
       MySqlConnection  conn;
       MySqlCommand cmd;
       MySqlDataReader reader;
       string conStr = String.Format("server{0};uid={1}; pwd{2};database={3}",serverName, DBUserID, Password, DBName);

       string query = String.Format("select col1, col2 from aTable where tblKey={0};", textBox1.Text);

        conn = new MySqlConnection(conStr);
        cmd = new MySqlCommand(query, conn);
        reader = cmd.ExecuteReader();

        listView1.Items.Clear()
        while(reader.Read())
        {
            listView1.Items.Add(
                new ListViewItem(new string[]
                                    {
                                        reader["col1"].ToString(),
                                        reader["col2"].ToString()
                                    });
        }
    }

Then get the selected data, by adding MouseDoubleClick event to your ListView

    private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;

        if (listView1.SelectedItems.Count < 1)
            return;

        ListViewItem itm = listView1.SelectedItems[0];

        //get selected value
        theValueSelection = itm.SubItems[0].Text;
        DialogResult = DialogResult.OK;
        Hide();
        //Next step: get 'theValueSelection' value from this 
        //form caller
    }

This is not the best way, but i hope it might help and i'm sorry for my poor english :)

Regards.

@imam: thanks for your answering about my query about on listView and MySQL connection.

However, the code you given is okay, actually the code that i need is when I double click the listView in Form2 the dataContent will be transfer to form1.

the ListView doubleClick in one Form is I got it already.

If you have an Idea in my query , please help.

I am happy that you given me a chance to share your knowledge.

Steps:
1. Form1 click popup button to send to form2
2. Form2 show up, then type the idnumber to search the data.
3. the data search in textbox through search button will be send to listView1.
4. After Search and the Data in ListView1, I will double click the Data.
5. Double click the ListView1, then the Data Will send to form1 txtbox1 for ID.
6. done.

PS: I am not in English Communicator.

Regards,

Darryl

Based on your explanation, here is the steps i have in my mind :

  1. On Form1.ButtonPopUp Clicked event, Create Form2 instance
  2. Acquire the DialogResult from frmSearhPopUp.ShowDialog() call
  3. If the DialogResult equals OK, set Form1 txtIDNumber.Text with your defined field on Form2 that hold the item selection value
  4. Continue with your query to fill up Form1 data based on current txtIDNumber.Text value

Code on Form1:

private void ButtonPopUp_Click(object sender, EventArgs e)
    {
        Form2 frmSearchPopUp = new Form2();

        DialogResult srcResult = frmSearchPopUp.ShowDialog();

        //The execution will continue here after you 
        //doubleclick listView1 on frmSearchPopUp
        //or close it

        if (srcResult == DialogResult.OK)
        {
            txtIDNumber.Text = frmSearchPopUp.UserSelectedResult;

            //Continue to next query based on current txtIDNumber.Text value
        }
    }

Code on Form2 is the same code with my previous post, as an addition to keep listView1 selected value i add userSelectedResult field on Form2

public partial class Form2 : Form
{
    //Field that hold user selection on listView1 
    public string userSelectedResult;   
        .
        .
        .

    public void LoadData()
    {
        //Let's Skip load data part
           .
           .
           .
    }

    private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;
        if (listView1.SelectedItems.Count < 1)
            return;
        ListViewItem itm = listView1.SelectedItems[0];

        //keep the selected value, assuming that you need
        //to obtain column1 value
        userSelectedResult = itm.SubItems[0].Text;

        DialogResult = DialogResult.OK;
        Hide();
    }
}

If this explanation doesn't suit your need, please let me know :)

Regards.

As far as child-parent form communication. You could use events, which I think may be your best option.

In my example, you will have 3 classes: "parentFrm", "childFrm", and "ValueUpdatedEventArgs".

ValueUpdatedEventArgs.cs

//ValueUpdatedEventArgs.cs
using System;
using System.Collection.Generic;
using System.Text;

namespace myNamespace1;
{
     public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

     public class ValueUpdatedEventArgs : System.EventArgs
     {
        private string _myData1;

        //---------------------------------------
        //this is just a normal class constructor
        //---------------------------------------

        public ValueUpdatedEventArgs(string newValue)
        {
             this._myData1 = newValue;
        }//constructor

        public string MyData1
        {
            get
            {
                return this._myData1;
            }//get
        }//method

     }//class
}//namespace

In the below code, for your purposes, change myTextBox_TextChanged(object sender, EventArgs e) to listView1_MouseDoubleClick(object sender, MouseEventArgs e)

childFrm.cs

//childFrm.cs --child form
using System;
using System.Collection.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace myNamespace1;
{

     public partial classchildFrm : Form
     {
        //--------------------------------------------
        // event interested parties can register with 
        // to know when value is updated.
        //--------------------------------------------

        public event ValueUpdatedEventHandler ValueUpdated;



        private void myTextBox_TextChanged(object sender, EventArgs e)
        {



            // the following lines are the ones to be 
            // added within the event
            // you want to use to update the value. In 
            // this case, we use the textbox
            // TextChanged event and set the value to 
            // 'myTextBox.Text.ToString()'
            // the data type of this variable needs to 
            // be the same data type
            // that is defined in 
            // 'ValueUpdatedEventArgs.cs'

            string myValue = "some new value";
            ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(myValue);
            ValueUpdated(this, valueArgs);



        }//myTextBox_TextChanged

     }//class
}//namespace

parentFrm.cs

using System;
using System.Collection.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace myNamespace1;
{

     public partial class parentFrm : Form
     {

        string dataValueToUpdate;

        private void myButton_Click(object sender, EventArgs e)
        {
            //create a new child form
            childFrm mychildFrm;
            mychildFrm = new childFrm();

            //add listener
            mychildFrm.ValueUpdated += new ValueUpdatedEventHandler(mychildFrm_ValueUpdated);
            mychildFrm.ShowDialog();
        }//method


        // event handler--this will occur
        // any time the firing event occurs
        // in the childFrm

        private void mychildFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
        {

            // MyData1 is the get method in 
            // 'ValueUpdatedEventArgs.cs'

            dataValueToUpdate = e.MyData1; 


            //  could update textbox here instead of updating a
            //  string value as I have done


            //  don't forget to call "Refresh" for the textboxt

            //  myTextBox.Text = e.MyData1;
            //  myTextBox.Refresh();


        }//event handler
     }//class
}//namespace

*Note: You could change ValueUpdatedEventArgs.cs to pass a class and/or other data types.

Edited 2 Years Ago by cgeier: add comment

@cgeier: I tried your code, it's okay, I have a problem on this. How do I know that I get the data in ListView in Form2 to transfer in Form1?

what do your mean

 string myValue = "some new value";

this?

Please help..

Regards,
Darryl

@imam:

I can't perform the code you given..

  1. If the DialogResult equals OK, set Form1 txtIDNumber.Text with your defined field on Form2 that hold the item selection value

    if (srcResult == DialogResult.OK)
    {
    txtIDNumber.Text = frmSearchPopUp.UserSelectedResult;
    //Continue to next query based on current txtIDNumber.Text value
    }

the TxtIDnumber.Text is the TextBox on the form1 right?.

my point of is in form1 I will click the button to popup the form2. in form2 there are fields the texbox field , button and listview1.

in the form2 i need a transaction to implement, when Type the data to form2 textbox to search, the data will be popup in listView1,. After that, I will doubleclick the listView1 and then the Data Will be send to form1 textboxIdNumber.

Base on your examples, It is Okay, It's near to get what I want,.

UserSelectedResult - for this what is all about? in form1 this code is error..

regards,

Darryl

the TxtIDnumber.Text is the TextBox on the form1 right?.

Yap, it's a TextBox on Form1, the name is based on your image post

UserSelectedResult - for this what is all about? in form1 this code is error..

if you like to, please provide the error description so we can trace its actual cause, here is some casual error that might happen

  1. C# is a Case-Sensitive language, so it is not possible to use different letter case to access same variable, which is i did it on my earlier post, my bad darryInuyda, sorry :)
    so instead of using this code (example Form1 line-13)
    txtIDNumber.Text = frmSearchPopUp.UserSelectedResult;
    try this (the difference is on u letter case)
    txtIDNumber.Text = frmSearchPopUp.userSelectedResult;

  2. Another possibility that on Form2, you hasn't declare public string userSelectedResult; yet, review my earlier post in Code on Form2 line-4.

Hope this help

Regard.

@imam1: I got it. thanks ;

How about if I obtain all columns in ListView1? it is possible?

I tried to perform, but the result it is not good.

Regards,
Darryl

simply declare some other variables on form2 to obtain every column value

or you can define an entity object to store row details then to assign it to ListViewItem.Tag property for later use

//a class definition that hold search result entity
public class SearchResult
{
    public string idNumber;
    public string firstName;
    public string MI;
    public string lastName;
}


//when populating data, keep every columns information
//in a SearchResult instance for every returned row
//into ListViewItem.Tag property
while(reader.Read())
{
    SearchResult src = new SearchResult();
    src.idNumber = reader["id"].ToString();
    src.firstName = reader["firstName"].ToString();
    src.MI = reader["MI"].ToString();
    src.lastName = reader["lastName").ToString();

    ListViewItem lvi = new ListViewItem(...);

    lvi.Tag = src;

    listView1.Items.Add(lvi);
}


//remember to change the userSelectionResult on Form2 
// from string to SearchResult type
    public SearchResult userSelectedResult;

//in listView1_MouseDoubleClick, instead of accessing SubItems array,
//use selecteditem tag property to obtain stored object 
    .
    .
    userSelectedResult = (SearchResult)itm.Tag;

//when obtaining the selection on Form1 do this
    .
    .
    .
    if(frmSearchPopUp.DialogResult == DialogResult.OK)
    {
        SearchResult result = (SearchResult)frmSearchPopup.userSelectedResult;
    }

simply declare some other variables on form2 to obtain every column value

or you can define an entity object to store row details then to assign it to ListViewItem.Tag property for later use

//a class definition that hold search result entity
public class SearchResult
{
    public string idNumber;
    public string firstName;
    public string MI;
    public string lastName;
}


//when populating data, keep every columns information
//in a SearchResult instance for every returned row
//into ListViewItem.Tag property
while(reader.Read())
{
    SearchResult src = new SearchResult();
    src.idNumber = reader["id"].ToString();
    src.firstName = reader["firstName"].ToString();
    src.MI = reader["MI"].ToString();
    src.lastName = reader["lastName").ToString();

    ListViewItem lvi = new ListViewItem(...);

    lvi.Tag = src;

    listView1.Items.Add(lvi);
}


//remember to change the userSelectionResult on Form2 
// from string to SearchResult type
    public SearchResult userSelectedResult;

//in listView1_MouseDoubleClick, instead of accessing SubItems array,
//use selecteditem tag property to obtain stored object 
    .
    .
    userSelectedResult = (SearchResult)itm.Tag;

//when obtaining the selection on Form1 do this
    .
    .
    .
    if(frmSearchPopUp.DialogResult == DialogResult.OK)
    {
        SearchResult result = (SearchResult)frmSearchPopup.userSelectedResult;
    }

Ok. I've made an example specific to your situation. I didn't do the database data retrieval however. I'll let you work on that part. I've made a note of where you should do the database retrieval (in SearchMemberFrm.cs). To run my example you will need the following.

On "Form1.cs":

  • Textbox named: idNumberTextBox
  • Textbox named: firstNameTextBox
  • Textbox named: miTextBox
  • TextBox named: lastNameTextBox
  • Button named: searchBtn

On "SearchFrm.cs":

  • Button named: searchBtn
  • ListView named: listView1

*Note: listView1 needs to contain (at least) 4 columns.

MemberInfo.cs

    public class MemberInfo
    {
        private string _idNumber = string.Empty;
        private string _firstName = string.Empty;
        private string _mi = string.Empty;
        private string _lastName = string.Empty;
        private string _mobileNumber = string.Empty;
        private string _email = string.Empty;
        private string _researchDirectorHead = string.Empty;
        private string _universityPresident = string.Empty;
        private string _mailingAddress = string.Empty;

        public string idNumber
        {
            get
            {
                return this._idNumber;
            } //get

            set
            {
                this._idNumber = value;
            } //set
        } //idNumber

        public string firstName
        {
            get
            {
                return this._firstName;
            } //get

            set
            {
                this._firstName = value;
            } //set
        } //firstName

        public string mi
        {
            get
            {
                return this._mi;
            } //get

            set
            {
                this._mi = value;
            } //set
        } //mi

        public string lastName
        {
            get
            {
                return this._lastName;
            } //get

            set
            {
                this._lastName = value;
            } //set
        } //lastName

        public string mobileNumber
        {
            get
            {
                return this._mobileNumber;
            } //get

            set
            {
                this._mobileNumber = value;
            } //set
        } //mobileNumber

        public string email
        {
            get
            {
                return this._email;
            } //get

            set
            {
                this._email = value;
            } //set
        } //email

        public string researchDirectorHead
        {
            get
            {
                return this._researchDirectorHead;
            } //get

            set
            {
                this._researchDirectorHead = value;
            } //set
        } //researchDirectorHead

        public string universityPresident
        {
            get
            {
                return this._universityPresident;
            } //get

            set
            {
                this._universityPresident = value;
            } //set
        } //universityPresident

        public string mailingAddress
        {
            get
            {
                return this._mailingAddress;
            } //get

            set
            {
                this._mailingAddress = value;
            } //set
        } //mailingAddress

    }//class

ValueUpdatedEventArgs.cs

     public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

     public class ValueUpdatedEventArgs : System.EventArgs
     {
        private MemberInfo member;

        public ValueUpdatedEventArgs(MemberInfo member)
        {
             this.member = member;
        }//constructor

        public MemberInfo GetMember
        {
            get
            {
                return this.member;
            }//get
        }//method

     }//class

Form1.cs

    public partial class Form1 : Form
    {
        MemberInfo member = new MemberInfo();

        public Form1()
        {
            InitializeComponent();
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            SearchMemberFrm mySearchMemberFrm = new SearchMemberFrm();

            //add listener
            mySearchMemberFrm.ValueUpdated += new ValueUpdatedEventHandler(mySearchMemberFrm_ValueUpdated);
            mySearchMemberFrm.ShowDialog();

            //mySearchMemberFrm.Show();
        }

        //event handler
        private void mySearchMemberFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
        {
            member = e.GetMember; //this is the get method in 'ValueUpdatedEventArgs.cs'

            idNumberTextBox.Text = member.idNumber;
            firstNameTextBox.Text = member.firstName;
            miTextBox.Text = member.mi;
            lastNameTextBox.Text = member.lastName;

            // ToDo: add the rest

        }//event handler
    }

SearchMemberFrm.cs

    public partial class SearchMemberFrm : Form
    {
        //event interested parties can register with 
        //to know when value is updated.
        public event ValueUpdatedEventHandler ValueUpdated;

        private MemberInfo member = new MemberInfo();

        //List to hold member's info
        private List<MemberInfo> memberList = new List<MemberInfo>();


        public SearchMemberFrm()
        {
            InitializeComponent();
        }//initialize


        private void searchBtn_Click(object sender, EventArgs e)
        {


            listView1.Items.Clear();

            //---------------------------------------------
            // this is where you will retrieve your data
            // from the database.
            //
            // Put data into memberList
            //
            // I've hard-coded some data for testing.
            //---------------------------------------------


            member = new MemberInfo();
            member.idNumber = "123";
            member.firstName = "John";
            member.mi = "B";
            member.lastName = "Doe";

            memberList.Add(member);

            member = new MemberInfo();
            member.idNumber = "456";
            member.firstName = "Sam";
            member.mi = "B";
            member.lastName = "Good";

            memberList.Add(member);

            member = new MemberInfo();
            member.idNumber = "789";
            member.firstName = "Jane";
            member.mi = "G";
            member.lastName = "Doe";

            memberList.Add(member);



            //---------------------------------------------
            // populate list view using memberList
            //---------------------------------------------
            foreach (MemberInfo info in memberList)
            {

                ListViewItem myListViewItem = new ListViewItem();
                myListViewItem.Text = info.idNumber;
                myListViewItem.SubItems.Add(info.firstName);
                myListViewItem.SubItems.Add(info.mi);
                myListViewItem.SubItems.Add(info.lastName);

                listView1.Items.Add(myListViewItem);
            }//foreach



        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //get currently selected item from listView1
            ListViewItem currentItem = listView1.GetItemAt(e.X, e.Y);


            //return if an item is not selected
            if (currentItem == null)
            {
                return;
            }//if

            Console.WriteLine("currentItemIndex: " + currentItem.Index);

            //MessageBox.Show("The selected idNumber is: '" + currentItem.Text + "'; index: " + currentItem.Index);

            //set member to the row the user double-clicked
            member = (MemberInfo)memberList[currentItem.Index];


            //send our event with the member data
            ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(member);
            ValueUpdated(this, valueArgs);
        }


    }

Edited 2 Years Ago by cgeier: re-formatted

Here is an updated version of "SearchMemberFrm.cs". It uses a DataGridView instead of ListView. I think that DataGridView is a better option.

"SearchMember.cs" requires the following:

  • Button named: searchBtn
  • DataGridView named: dataGridView1

*Note: Just add a DataGridView. Do NOT configure any columns or add any events. The configuration and events are in the code.

The database retrieval part of the code that is commented out is untested.

SearchMemberFrm.cs

//  download and install mySQL connector
//  http://dev.mysql.com/downloads/connector/net/
//
//  for .NET 4.0
//  Create reference: Select "Project" => Reference => Browse
//  => C:\Program Files\MySQL\MySQL Connector Net 6.8.3\
//        Assemblies\v4.0\MySQL.Data.dll

//  add "using MySql.Data.MySqlClient;" above
//
//  may also need to create reference to: MySQL.web.dll
//  
// add the below "using" statement to your searchMemberFrm class
// using MySql.Data.MySqlClient;


    public partial class SearchMemberFrm : Form
    {
        //event interested parties can register with 
        //to know when value is updated.
        public event ValueUpdatedEventHandler ValueUpdated;

        private MemberInfo member = new MemberInfo();

        private DataTable dt;


        public SearchMemberFrm()
        {
            InitializeComponent();
        }//initialize



        private void SearchMemberFrm_Load(object sender, EventArgs e)
        {

            //set minimum size for window
            this.MinimumSize = new System.Drawing.Size(350, 250);

            //http://social.msdn.microsoft.com/Forums/windows/en-US/a44622c0-74e1-463b-97b9-27b87513747e/windows-forms-data-controls-and-databinding-faq?forum=winformsdatacontrols#faq13

            //add listener for CellDoubleClick
            this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick);

            //change anchor property so dataGridView1 resizes with the window
            this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));

            //hide first column that contains '*'
            dataGridView1.RowHeadersVisible = false;

            //select whole row when cell is clicked
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            //eliminate blank first row
            //http://msdn.microsoft.com/en-us/library/ms171605(v=vs.90).aspx
            // Configure the DataGridView so that users can manually change  
            // only the column widths, which are set to fill mode. 
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.AllowUserToResizeRows = false;
            dataGridView1.RowHeadersWidthSizeMode =
                DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            dataGridView1.ColumnHeadersHeightSizeMode =
                DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView1.AutoSizeColumnsMode =
                DataGridViewAutoSizeColumnsMode.Fill;

            //delete any existing columns
            dataGridView1.Columns.Clear();

            //makes it so the gray blank area of dataGridView1 is unnoticeable
            dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;
            dataGridView1.BorderStyle = BorderStyle.None;

            //add data columns so table shows
            AddDataColumns();
        }


        private void AddDataColumns()
        {
            // clears previous data
            // preventing duplicates
            dataGridView1.DataSource = null;

            if (dt != null)
            {
                dt.Reset();
            }//if

            //-----------------------------------------------
            // Add columns to "MemberTbl" datatable
            //
            // Add additional columns here--if needed
            //-----------------------------------------------
            dt = new DataTable("MemberTbl");
            dt.Columns.Add("ID Number", typeof(string));
            dt.Columns.Add("First Name", typeof(string));
            dt.Columns.Add("M.I.", typeof(string));
            dt.Columns.Add("Last Name", typeof(string));

            //-----------------------------------------------
            // end of adding columns
            //-----------------------------------------------


            //set columns readonly
            foreach (DataColumn col in dt.Columns)
            {
                col.ReadOnly = true;
            }

            //bind source to our dataset
            dataGridView1.DataSource = dt;


            //prevent first row / first cell from
            //being highlighted
            dataGridView1.CurrentCell = null;
        }//AddDataColumns


        private void searchBtn_Click(object sender, EventArgs e)
        {
            //call AddDataColumns when button is clicked
            //ensures that there are no duplicate rows
            AddDataColumns();

            /*

            //-----------------------------------------------
            // Retrieve data from database
            // and populate datagridview1
            //
            // see http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp
            // and http://dev.mysql.com/doc/refman/5.1/en/connector-net-info.html
            // for more info
            //------------------------------------------------


            string myConnectionString = "Server=localhost;Database=memberDB;Uid=root;Pwd=password;";

            MySqlConnection connection = new MySqlConnection(myConnectionString);


            try
            {
                connection.Open();

                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "Select * from member";
                MySqlDataAdapter adap = new MySqlDataAdapter(cmd);

                //put data into data table
                adap.Fill(dt);

                //alternatively use a data set
                //to put data into data table

                //DataSet ds = new DataSet();
                //adap.Fill(ds);
                //dataGridView1.DataSource = ds.Tables[0].DefaultView;
            }//try
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error - " + this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); 
                //throw ex;
            }//catch
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }//if
            }//finally

            */


            //------------------------------------------------
            // Hard-coded test data.
            //
            // Remove or comment out if retrieving data
            // from database.
            //------------------------------------------------


            //List to hold member's info
            List<MemberInfo> memberList = new List<MemberInfo>();

            //memberList.Clear(); //clear old data

            member = new MemberInfo();
            member.idNumber = "123";
            member.firstName = "John";
            member.mi = "B";
            member.lastName = "Doe";

            memberList.Add(member);

            member = new MemberInfo();
            member.idNumber = "456";
            member.firstName = "Sam";
            member.mi = "B";
            member.lastName = "Good";

            memberList.Add(member);

            member = new MemberInfo();
            member.idNumber = "789";
            member.firstName = "Jane";
            member.mi = "G";
            member.lastName = "Doe";

            memberList.Add(member);

            foreach (MemberInfo info in memberList)
            {
                //create a new datarow
                DataRow dr = dt.NewRow();

                dr[0] = info.idNumber;
                dr[1] = info.firstName;
                dr[2] = info.mi;
                dr[3] = info.lastName;

                //add row to table
                dt.Rows.Add(dr);
            }//foreach

            //------------------------------------------------
            // end of hard-coded data
            //------------------------------------------------


            if (dataGridView1.Rows.Count >= 1)
            {

                // de-select row 0, column 0.
                // eliminates highlighting on row 0, col 0
                // or eliminates highlighting of entire row if 
                //dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dataGridView1.Rows[0].Cells[0].Selected = false;
            }//if
        }


        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //Console.WriteLine("b: You double-clicked row: " + dataGridView1.CurrentRow.Index);

            //MessageBox.Show("You selected row: " + dataGridView1.CurrentRow.Index);

            //set member to the row the user double-clicked
            member.idNumber = (string)dataGridView1.CurrentRow.Cells[0].Value;
            member.firstName = (string)dataGridView1.CurrentRow.Cells[1].Value;
            member.mi = (string)dataGridView1.CurrentRow.Cells[2].Value;
            member.lastName = (string)dataGridView1.CurrentRow.Cells[3].Value;

            ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(member);
            ValueUpdated(this, valueArgs);

        }

    }

Edited 2 Years Ago by cgeier: added comment

Here's a program I wrote to remove the line numbers from code posted on this site. It will save you some time copying the code to run my examples.

To use "Form1.cs" you need a form that contains:

  • TextBox named: userMatchPatternTextBox
  • Button named: resetBtn
  • Button named: runBtn
  • Button named: clearAllBtn
  • RichTextBox named: inputRichTextBox
  • RichTextBox named: outputRichTextBox

*Note: Need to add using System.Text.RegularExpressions;

Form1.cs

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //override ctl-v
        //so we can process the data--ensuring unicode data is properly
        //converted

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
        {
            if(keyData == (Keys.Control | Keys.V))
            {
                 //your implementation
                inputRichTextBox.Text = GetClipboardData();

                 return true;
            } 
            else 
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
        }//ProcessCmdKey

        private void runBtn_Click(object sender, EventArgs e)
        {
            String userDefinedMatchPattern = userMatchPatternTextBox.Text.ToString();

            string userData = inputRichTextBox.Text.ToString();

            string[] userDataArray = userData.Split(new string[] { "\r\n","\n","\r"}, StringSplitOptions.None);


            Regex rgx = new Regex(userDefinedMatchPattern);

            string output = string.Empty;
            foreach (string lineData in userDataArray)
            {
                string result = rgx.Replace(lineData, string.Empty);

                output += result + System.Environment.NewLine;
            }//foreach

            outputRichTextBox.Text = output;
        }

        private void resetBtn_Click(object sender, EventArgs e)
        {
            userMatchPatternTextBox.Text = "^\\s?\\d+\\.";
        }

        private void clearAllBtn_Click(object sender, EventArgs e)
        {
            outputRichTextBox.Text = string.Empty;
            inputRichTextBox.Text = string.Empty;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            userMatchPatternTextBox.Text = "^\\s?\\d+\\.";
        }

        private string GetClipboardData()
        {
            string cbText = string.Empty;
            bool cbContainsUnicodeText = false;
            bool cbContainsText = false;

            IDataObject cbDataObject = Clipboard.GetDataObject();

            string[] cbObjectTypes = cbDataObject.GetFormats();

            foreach (string cbObject in cbObjectTypes)
            {
                //Console.WriteLine("obj: " + cbObject);


                if (string.Compare(cbObject, "UnicodeText") == 0)
                {
                    cbContainsUnicodeText = true;
                }//if

                else if (string.Compare(cbObject, "Text") == 0)
                {
                    cbContainsText = true;
                }//else if

            }//foreach


            if (Clipboard.ContainsText())
            {

                if (cbContainsUnicodeText)
                {
                    cbText = Clipboard.GetData(System.Windows.Forms.DataFormats.UnicodeText).ToString();
                }//if
                else if (cbContainsText)
                {
                    cbText = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);
                }//else if
            }
            return cbText;

        }//GetClipboardData


    }

To use it, highlight the code you want to copy from this site and then press ctl-c. Then paste it to the inputRichTextBox on "Form1" using ctl-v. Click runBtn. Re-formatted text is in outputRichTextBox.

Edited 2 Years Ago by cgeier: re-format

@imam: i tried your code example, but I can't understand, where I can input the code.

Hi Everyone:

can i asked your help, please check the image below:

  1. Membership form for new applicants.
    a. After I saved the registration for the new member I want to go the #2
  2. Search Members.
    a. Purpose: to select if the members is registered or not.
    b. Is the members is view, double click to transfer in membership form.
  3. Back to membership form
    a. After select the data in Search Membership.
    i. Show The Id Number, First, Middle, Last and address in text field
  4. After the Data view, select the Button add organization transaction.
  5. Organization form
    a. View the Personal Details
    b. Select the Organization type
    c. Payment option
  6. Go to the Organization and Select
    a. Back to organization form
  7. Go to the Payment form
    a. To pay the transaction

    f61a68254b1441f0fa37f09d83d85857

@castajiz: the main problem on that is bring value from popup window to parent window form.

regards
Darryl

Edited 2 Years Ago by darrylnuyda: update content

See my tutorial on form communication.

This one is for vb .net. I don't have time to write one for C# right now. The code I previously posted in your question (above) is how do it in C#. If you read the one for vb .net it should offer you an explanation of the different parts.

This article has been dead for over six months. Start a new discussion instead.