|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article will explain how to select a row on a Data Grid in one Windows Form, and populate controls in another Windows Form using a Delegate.The example in this article comes from trying to find a way to pass data between two separate forms that were located in a custom plug-in I created. Both forms did not have a parent form so to speak, that I could use to act as a bridge between the two. ' BackgroundThere have been lots of articles describing what delegates are and how they are set up, I'll leave that to the reader and will just jump right into the code. ' Using the codeThe code in this example consists of a Data Grid located in In FormBottom.cs we define our delegate. public delegate void CustomRowHandler(
object sender, CustomRowEventArgs e);
and the event handler, which is defined as public static event CustomRowHandler CustomRow;
The public class CustomRowEventArgs : EventArgs
{
DataSet dataSet;
DataGrid grid;
int row;
public CustomRowEventArgs(
DataSet DSet,DataGrid Grid,int Row)
{
grid = Grid;
row = Row;
dataSet = DSet;
}
public DataSet DSet
{
get { return dataSet; }
}
public DataGrid Grid
{
get { return grid; }
}
public int Row
{
get { return row; }
}
}
We initialize the Data Grid when the form loads. See the project example code for more information on private void FormBottom_Load(
object sender, System.EventArgs e)
{
BindFamousPeople();
dgts = new DataGridTableStyle();
dgts.MappingName = "People";
dataGrid1.TableStyles.Add(dgts);
}
We bind a public void dataGrid_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
int rowIndex = dgts.DataGrid.CurrentRowIndex;
if (CustomRow != null)
{
CustomRow(this, new CustomRowEventArgs(
dataSet1,dataGrid1,rowIndex));
}
In FormTop.cs we include the following code. By use of a delegate, the FormBottom.CustomRow += new DelegateExample.CustomRowHandler(
customHandler_CustomRow);
The private void customHandler_CustomRow(object sender,
DelegateExample.CustomRowEventArgs e)
{
DataSet dSet = e.DSet;
DataGrid grid = e.Grid;
int row = e.Row;
textBox2.Text = grid[e.Row,0].ToString();
textBox3.Text = grid[e.Row,1].ToString();
textBox4.Text = grid[e.Row,2].ToString();
}
ConclusionThat's it. I have kept the source code very simple so you should easily be able to see what is going on. The project files and source code for the article are provided above.
|
||||||||||||||||||||||||||||||||||||||||