I recently started using C# in WPF (.NET Core). I am very new in using C# so I apologize if the question is relative easy to answer. Briefly I would like to create a button that when clicked by the user will generate the count of rows of a specific table.
My code so far (using the WPF (.NET Core) in Visual Studio 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
namespace TestEnvironment
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private dynamic connectionString;
public ConnectionStringValue()
{
connectionString();
static void connectionString()
{
string connectionString = "Data Source=youServerHere;Initial Catalog=YourDataBase;Integrated Security=True;"; #access it with Windows Authentication
}
}
SqlConnection sqlCon = new SqlConnection(connectionString);
sqlCon.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM tblProduct");
sqlCommand.Connection = sqlCon;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Count.Text = RecordCount;
}
}
}
My first error that I cannot overpass is the variable connectionString for which I get the error: CS0236 A field initializer cannot reference the non-static field, method, or property 'MainWindow.connectionString'
To fix this I tried to create a private dynamic object named connectionString, but still my error is unresolved.
Thank in advance for any advise and I apologize again for my inexperience with C#.
Code update
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private string connectionString;
public ConnectionStringValue()
{
static void connectionString()
{
connectionString = "Data Source=youServerHere;Initial Catalog=YourDataBase;User ID=sa; Password=123;";
}
}
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM tblProduct");
sqlCommand.Connection = sqlConnection;
int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Count.Text = RecordCount;
}
}
}
Error 1: CS1520 Method must have a return type (for the ConnectionStringValue)
Error 2: CS1656 Cannot assign to 'connectionString' because it is a 'method group' + CS8422 A static local function cannot contain a reference to 'this' or 'base'. (both errors for connectionString string object)