How To Find Value In A 2D Array Using C#
In this C# Tutorial we will see How To Search And Find A Value Position Inside A Multidimensional Array Using For Loop + TextBox And Display The Positions Inside A RichTextBox On A Button Click Event In CSharp Programming Language And Visual Studio Editor.
Project Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Search_In_2D_Array : Form
{
public Search_In_2D_Array()
{
InitializeComponent();
}
// create 2D array
string[,] data;
private void Search_In_2D_Array_Load(object sender, EventArgs e)
{
// add data to the array
data = new string[,]{// 1 2 3 4
{"1","AAA","BBB","10"},//1
{"2","CCC","DDD","20"},//2
{"3","ZZZ","YYY","30"},//3
{"4","LLL","CCC","40"},
{"5","NNN","TTT","50"},
{"6","CCC","RRR","CCC"},
{"7","GGG","CCC","70"}//7
};
// display array data into richTextbox
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
richTextBox1.Text += data[i, j] + " - ";
}
richTextBox1.Text += "\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox2.Text = "";
// data.GetLength(0) = length of the first D (7)
for(int i = 0; i < data.GetLength(0); i++)
{
// data.GetLength(1) = length of the second D (4)
for (int j = 0; j < data.GetLength(1); j++)
{
if(textBox1.Text.Equals(data[i,j]))
{
richTextBox2.Text += "POSITION[" + i + " , " + j + "]";
}
}
}
}
}
}
OutPut:
Download Projects Source Code