First C# form app for me. I can write it in POSH, but I'm trying to graduate and understand C#. I know I have a long way to go, but if someone could help explain this, I would be grateful.
I have a simple SQL table with the following: CLIENT, INPATH, OUTPATH, LIMITERS (PK)
LIMITERS have Unique Values
For each CLIENT, INPATH and OUTPATH are the same.
I am trying to create a form that does the following:
Display a listbox with distinct CLIENT -Working
--- The rest is not working ---
On ListBox Click:
Fill TextBox with INPATH for selected CLIENT
Fill TextBox with OUTPATH for selected CLIENT
Fill ListBox with LIMITERS for selected CLIENT
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;
using Microsoft.Data.SqlClient;
namespace DSI_SFTP_FrontEnd
{
public partial class ClientMain : Form
{
private SqlDbConnect con;
public ClientMain()
{
InitializeComponent();
con = new SqlDbConnect();
con.SqlQuery("Select Distinct CLIENT from Client_Inf");
clientListBoxValues.Items.Clear();
foreach (DataRow dr in con.QueryEx().Rows)
{
clientListBoxValues.Items.Add(dr[0].ToString());
}
}
private void clientListBoxValues_SelectedIndexChanged(object sender, EventArgs e)
{
string text = clientListBoxValues.GetItemText(clientListBoxValues.SelectedItem);
if (text != null)
{
InitializeComponent();
string sql = $"Select INPATH, OUTPATH, LIMITERS from Client_Inf where CLIENT = '{text}'";
con = new SqlDbConnect();
con.SqlQuery(sql);
DataTable dataTable = con.QueryEx();
{
inPathTextBoxValue.Text = dataTable.Rows[0]["INPATH"].ToString();
outPathTextBoxValue.Text = dataTable.Rows[0]["OUTPATH"].ToString();
}
foreach (DataRow dr in dataTable.Rows)
{
limitersListBoxValues.Items.Add(dr[2].ToString());
}
}
}
private void createNewbutton_Click(object sender, EventArgs e)
{
NewClientForm frm = new NewClientForm();
frm.ShowDialog();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
SqlDbConnect.cs
using System.Data;
namespace DSI_SFTP_FrontEnd
{
public class SqlDbConnect
{
private SqlConnection _con;
public SqlCommand _cmd;
private SqlDataAdapter _da;
private DataTable _dt;
public SqlDbConnect()
{
_con=new SqlConnection("Server=<SERVER>;Database=<DB>;Trusted_Connection=True;TrustServerCertificate=True;");
_con.Open();
}
public void SqlQuery(string queryText)
{
_cmd= new SqlCommand(queryText, _con);
}
public DataTable QueryEx()
{
_da = new SqlDataAdapter(_cmd);
_dt= new DataTable();
_da.Fill(_dt);
return _dt;
}
public void NonQueryEx()
{
_cmd.ExecuteNonQuery();
}
}
}
The problem is that you are calling InitializeComponent() in clientListBoxValues_SelectedIndexChanged. InitializeComponent() creates the controls, .i.e., the TextBoxes and ListBoxes, etc. The effect is that you are creating another set of those controls every time the selected index of the ListBox changes.
InitializeComponent() must be called once in the constructor ClientMain() and nowhere else!
Related
I am new to C#, and 1st post here. I'm am writing a windows form app to be used as a database entry tool. to do this I'm connecting to an access database to read lists and capture new inputs
the error I'm getting is:
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'
at
OleDbDataReader reader = cmd.ExecuteReader();
The code of the form that is driving the fault is:
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;
using System.Data.OleDb;
namespace Metrics_Data
{
public partial class Login : Form
{
Welcome conndata = new Welcome();
public Login()
{
InitializeComponent();
}
private void btn_exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Login_Load(object sender, EventArgs e)
{
}
private void btn_login_Click(object sender, EventArgs e)
{
//Verify Password and UserID
string Password = null;
OleDbCommand cmd = new OleDbCommand("SELECT * from [Users] WHERE UserID = #UserID",conndata.myconn);
cmd.Parameters.Add("#UserID", OleDbType.VarChar).Value = txt_userid;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Password = reader["User_Password"].ToString();
}
reader.Close();
cmd.Dispose();
//Load Next Form
UserHome userHomeform = new Metrics_Data.UserHome();
this.Hide();
userHomeform.ShowDialog();
}
}
}
The code that connects from the welcome screen is:
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;
using System.Data.OleDb;
using Microsoft.Win32;
namespace Metrics_Data
{
public partial class Welcome : Form
{
public OleDbConnection myconn = null;
public Welcome()
{
try
{
InitializeComponent();
OleDbConnection myconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\148.96.211.237\GroupShares\Quality\Electronic Checksheets\MD.accdb;jet OLEDB:Database Password=""Warranty""");
myconn.Open();
lbl_Connstatus.Text = "Connected to DB";
p_dbconn.Visible = true;
}
catch(Exception)
{
MessageBox.Show("error connecting to DB");
btn_cfg.Visible = false;
btn_home.Visible = false;
btn_help.Visible = true;
}
}
class Variables
{
public static dynamic LoginType;
public static dynamic UserID;
public static dynamic Admin;
public static dynamic FirstUse;
public static dynamic Zone;
public static dynamic Shift;
public static dynamic Group;
public static dynamic CDate;
public static dynamic GateLevel;
public static dynamic CountermeasureID;
}
private void Welcome_Load(object sender, EventArgs e)
{
}
private void btn_help_Click(object sender, EventArgs e)
{
//If program is unable to connect with database, initiate sequence where computer's installed access database engine's are displayed in popups, then tell user that program cannot connect
//popups are displayed to help user. If no database engine popups are displayed, see the following URL for troubleshooting information:
//https://support.microsoft.com/en-us/help/2874601/can-t-use-the-access-odbc-driver-or-oledb-provider-outside-office-clic
//A possible fix to this problem is to install access runtime 2013. The URL below has the link to where it's stored locally:
//\\10.35.193.112\Open\AccessRuntime2013
//Update: This also resolves concerns for computers with MS Office 2016, in which the user will receive a popup indicating they have an OLEDB database engine, but the program still will
//not work. IT may be required to give users temporary administrative rights to install AccessRuntime2013.
string AccessDBAsValue = string.Empty;
RegistryKey rkACDBKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Classes");
if (rkACDBKey != null)
{
foreach (string subKeyName in rkACDBKey.GetSubKeyNames())
{
if (subKeyName.Contains("Microsoft.ACE.OLEDB"))
{
MessageBox.Show(Convert.ToString(subKeyName));
}
}
}
MessageBox.Show("The program was unable to connect to the database.");
}
private void btn_exit_Click(object sender, EventArgs e)
{
Environment.Exit(1);
}
private void btn_home_Click(object sender, EventArgs e)
{
Login loginform = new Metrics_Data.Login();
Variables.LoginType = "Data Entry";
loginform.ShowDialog();
}
Any ideas of what I am doing wrong here??? I have verified path to database and the connection string at initial connection does not give any errors, nor do I have any errors in the error space on visual studio.
Many Thanks!
As pointed out in the comments, your constructor is hiding the form property myconn with a local variable, so when you reference the form property, it will be null.
However, I'd be remiss if I did not suggest that you NOT store the connection in a form property. ADO.NET Connections are pooled and are generally cheap to create, so just create one when you need one and dispose of it (using using) when you're done with the query it's created for.
You can store the connection string in one place, but sharing connection objects is generally a bad idea.
Not using a shared connection will also make it simpler since you don't have to worry about checking if the connection is open or not, worrying about opening it twice, etc.
so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present 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;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.
I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}
I have designed a WinForm which is bound to my database using ADO.Net Entity Framework. On load my details form is populated with data from the database.
I can navigate through the items, however I can not add, save or update the item.
Below is the code for my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
cpdEntities dbcontext;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
cpd_recipientsBindingSource.DataSource = dbcontext.cpd_recipients.ToList();
}
private void cpd_recipientsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
dbcontext.SaveChanges();
}
}
}
Here is a simple example working with EntityFramework 4
How to Load:
using (var con = new cpdEntities())
{
cpd_recipientsBindingSource.DataSource = con.cpd_recipients.ToList();
}
How to Insert and Update:
if (cpd_recipientsBindingSource.Current == null) return;
using (var con = new cpdEntities())
{
var p = new Customer()
{
CustomerId = ((cpd_recipients)cpd_recipientsBindingSource.Current).Id,
CustomerIdNo = IdNoTextBox.Text,
CustomerName = CustomerNameTextBox.Text
};
var cus = new Customer();
if (p.CustomerId > 0)
cus = con.Customers.First(c => c.CustomerId == p.CustomerId);
cus.CustomerId = p.CustomerId;
cus.CustomerIdNo = p.CustomerIdNo;
cus.CustomerName = p.CustomerName;
if (p.CustomerId == 0)
con.Customers.AddObject(cus);
con.SaveChanges();
int i = cus.CustomerId;//SCOPE_IDENTITY
}
}
It looks like your re-instantiating your DbContext class in each of the events. Remove re-insantiating the DbContext from your saveItem event and give it a try again.
I'm implementing the code from the book to create a customized action pane in Excel
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
namespace ExcelWorkbook1
{
public partial class Sheet1
{
public Button customerButton = new Button();
public Button inventoryButton = new Button();
private void Sheet1_Startup(object sender, EventArgs e)
{
customerButton.Text = "Select a customer...";
inventoryButton.Text = "Check inventory...";
this.orderInfo.Selected +=
new Excel.DocEvents_SelectionChangeEventHandler(
OrderInfo_Selected);
this.orderInfo.Deselected +=
new Excel.DocEvents_SelectionChangeEventHandler(
OrderInfo_Deselected);
this.customerInfo.Selected +=
new Excel.DocEvents_SelectionChangeEventHandler(
CustomerInfo_Selected);
this.customerInfo.Deselected +=
new Excel.DocEvents_SelectionChangeEventHandler(
CustomerInfo_Deselected);
}
#region VSTO Designer generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Sheet1_Startup);
}
#endregion
void OrderInfo_Selected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Add(inventoryButton);
}
void OrderInfo_Deselected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Remove(inventoryButton);
}
void CustomerInfo_Selected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Add(customerButton);
}
void CustomerInfo_Deselected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Remove(customerButton);
}
}
}
However
the code this.order.Selected' is not regconized
Do you have any suggestion for me?
Thanks
Do you have a named range in your Sheet1 with name orderInfo?
If yes, is it generated in the code-behind? (Sheet1.Designer.cs)
Notice, that you misspeled the name of your member in the last sentence: should be 'this.orderInfo.Selected'