How to retrieve data in C# winforms when only database has changed using MongoDB? I Coded Using Visual Studio. I've Form1 that Has TextBox and Button To Insert Data Into Database. Form2 Have Label that shown last data in database
What I've Tried :
MongoDB :
Database Name : test_chat
Exist Collection : table1
/* Code in Form1 */
public partial class Form1 : Form
{
public static IMongoClient client;
public static IMongoDatabase db;
static String mongo_connStr = @"mongodb://127.0.0.1:27017";
public Form1()
{
InitializeComponent();
}
public static void Connect()
{
try
{
if (client == null)
{
client = new MongoClient(mongo_connStr);
db = client.GetDatabase("test_chat");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
Connect();
if (db == null)
{
MessageBox.Show("Database Not Connected!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
BsonDocument bDoc = new BsonDocument();
bDoc.Add("Form1", textBox1.Text);
var collection = db.GetCollection<BsonDocument>("table1");
collection.InsertOneAsync(bDoc).Wait();
textBox1.Text = String.Empty;
textBox1.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
/* Code in Form2 */
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Shown(object sender, EventArgs e)
{
Form1.Connect();
CallMain();
}
public async Task CallMain()
{
Form1.Connect();
var collection = Form1.db.GetCollection<BsonDocument>("table1");
using (var cursor = await collection.Find(new BsonDocument()).ToCursorAsync())
{
while(await cursor.MoveNextAsync())
foreach (BsonDocument doc in cursor.Current)
{
label1.Text = doc.GetElement(1).Value.ToString();
}
}
}
}