I'm having a problem with C# and sql connection. when it comes to C# I'm a noobie and have pretty much no idea what I'm doing :/ I am trying to follow a tutorial which explaines how to do everything step by step and for some reason it doesn't work when I try to do it on my database and application.
This is my Form1.cs
using System;
using System.Collections;
using System.Windows.Forms;
namespace Praca_Inzynierska
{
public partial class Form1 : Form
{
private Connection sqlCon = new Connection();
private ArrayList list = new ArrayList();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'restaurantDataSet2.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.restaurantDataSet2.Employees);
FillTextFieldsEmployees(1);
}
public void FillTextFieldsEmployees(int EmployeeID)
{
list = sqlCon.GetAllEmployees(EmployeeID);
textFirstName.Text = list[0].ToString();
textLastName.Text = list[1].ToString();
textAdress.Text = list[2].ToString();
textCity.Text = list[3].ToString();
textPhoneNumber.Text = list[4].ToString();
textEmail.Text = list[5].ToString();
textBirthDate.Text = list[6].ToString();
textAge.Text = list[7].ToString();
textGender.Text = list[8].ToString();
textTitle.Text = list[9].ToString();
textSalary.Text = list[10].ToString();
}
private void dataGridViewEmployees_CellClick(object sender, DataGridViewCellEventArgs e)
{
var currentRowIndex = dataGridViewEmployees.SelectedCells[0].RowIndex;
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
FillTextFieldsEmployees(currentIndex);
}
}
}
This is my class Connection
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace Praca_Inzynierska
{
public class Connection
{
private String connectionString = "Data Source = MAKSKOMP\\SQL2012EXP; Initial Catalog = Restaurant;Integrated Security = True";
public ArrayList GetAllEmployees(int EmployeeID)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
String query = "SELECT * FROM Employees WHERE EmployeeID = '" + EmployeeID +"'";
using (var command = new SqlCommand(query, connection))
{
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
connection.Close();
reader.Close();
return list;
}
}
}
}
}
and for some reason it breaks in this particular place
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
I have tried to debug it step by step and also it doesn't finish this loop
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
it ends on
Int16 Age = reader.GetInt16(8);
Since your code already uses a Data Bound grid, try binding the TextBox controls to the same binding source as well. It doesn't make much sense to fetch the data from the database when the data is already loaded into the grid...
Related
I'm create the application, but i have one question.
The client write the name of user in textbox, example 3 letters and search in database(access) and add the database.
Example: User: Rui.
and search in database all nameuser "Rui".
//libraries
using Microsoft.VisualStudio.OLE.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
List<string> Users = new List<string>();
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT* FROM MyTable WHERE Str(Lista_Pokemon) like '*{textBox1.Text}*'";
User.Clear();
//this code is invention, probably is wrong
for(int d=0; d<Stk.Count()-1; d++)
User.Add(...);
}
If you can help my thanks. This project is c#, net framework and the database is Access 2010. At the moment I dont create the class, but if you need tell my, i need created.
You need create a DbReader and move to next row until end:
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT * FROM MyTable WHERE Str(Lista_Pokemon) like '%{textBox1.Text}%'";
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["Lista_Pokemon"].ToString());
Threading user input into the query text is considered a dangerous practice in terms of security and also not logically unsafe.
It is better to act "according to the book" with parameters:
OleDbCommand STK = new OleDbCommand();
STK.Connection = conexao;
STK.CommandText = "SELECT * FROM tblCliente WHERE User like #userParameter";
STK.Parameters.AddWithValue("#userParameter", $"%{textBox1.Text}%")
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["User"].ToString());
Look at the following code.
The using operator is used here to release resources - this is important!
var dataSource = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Teste.accdb");
var builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.DataSource = dataSource;
var connectionString = builder.ToString();
var sql = "SELECT ..."; // place your query here
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
using (var command = new OleDbCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (int)reader["NÂșCliente"];
user.UserName = (string)reader["NomeUser"];
user.CodigoPostal = (string)reader["CodigoPostal"];
user.NIF = (string)reader["NIF"];
users.Add(user);
}
// return users; // Return data from method
}
}
This class is used for storing user data.
Change the property names and types to the ones you need.
class User
{
public int ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}
And, of course, use parameters in sql queries, as #dovid showed in his example.
Thanks Alexander Petrov and dovid, givend the solution to my problem. But i "found" the solution and i send.
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
OleDbCommand STK = new OleDbCommand("SELECT * FROM MyTable ORDER BY Id");
conexao.Open();
comando.Connection = STK;
var reader = comando.ExecuteReader();
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (reader["ClientNumber "]);
user.UserName= reader["UserName"];
user.CodigoPostal= reader["CodigoPostal"];
user.NIF= reader["NIF"];
users.Add(user);
}
class User
{
public string ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}
I'm trying to post a List from my Model so that within the Controller I can view all the contacts that are within the List.
I have tried many different ways, but for some reason I get the same error that the List is null, even though there is data within my Microsoft Access Database. Also, when I try to edit the data, I can do so, but I'm not able to view the data that was previously present within the text boxes of the Controller/View.
If some could please help me.
MODEL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
namespace CW2_Enterprise
{
public class Contact
{
OleDbConnection connection = new OleDbConnection();
public List<Contact> contacts = new List<Contact>();
String id;
String firstName;
String lastName;
String postcode;
String email;
String phone;
public Contact(string id, string firstName, string lastName, string postcode, string email, string phone)
{
this.ID = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Postcode = postcode;
this.Email = email;
this.Phone = phone;
}
public void addContacts(Contact contact)
{
string id = contact.ID;
string firstName = contact.FirstName;
string lastName = contact.LastName;
string postcode = contact.Postcode;
string email = contact.Email;
string phone = contact.Phone;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Contact VALUES ('" + id + "','" + firstName + "','" + lastName + "','" + postcode + "','" + email + "','" + phone + "')";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void viewContacts(Contact contact)
{
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Contact";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
contact.ID = reader["ID"].ToString();
contact.FirstName = reader["FirstName"].ToString();
contact.LastName = reader["LastName"].ToString();
contact.Postcode = reader["Postcode"].ToString();
contact.Email = reader["Email"].ToString();
contact.Phone = reader["Phone"].ToString();
contact.contacts.Add(contact);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void find(Contact contact)
{
string id = contact.ID;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Contact WHERE ID='" + contact.ID + "'";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public void editContacts(Contact contact)
{
string id = contact.ID;
string firstName = contact.FirstName;
string lastName = contact.LastName;
string postcode = contact.Postcode;
string email = contact.Email;
string phone = contact.Phone;
try
{
connection.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\Database_2.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string see = "UPDATE Contact SET FirstName='" + firstName + "', LastName='" + lastName + "', Postcode='" + postcode + "', Email='" + email + "', Phone='" + phone + "' WHERE ID='" + id + "'";
command.CommandText = see;
OleDbDataReader reader = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Postcode { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public List<Contact> ContactsView { get; set; }
}
}
View/Controller (Partial Class)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CW2_Enterprise
{
public partial class viewContacts : Form
{
Contact contact = new Contact();
ComboBox comboBox = new ComboBox();
public viewContacts()
{
InitializeComponent();
}
private void viewContacts_Load(object sender, EventArgs e)
{
comboBox.Location = new System.Drawing.Point(10, 10);
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.Size = new System.Drawing.Size(136, 81);
this.Controls.Add(comboBox);
comboBox.Items.Add(contact.FirstName);
contact.viewContacts(contact);
}
}
}
Edit Contacts View/Controller (Partial Class)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CW2_Enterprise
{
public partial class editContacts : Form
{
TextBox idBox = new TextBox();
TextBox firstNameBox = new TextBox();
TextBox lastNameBox = new TextBox();
TextBox postcodeBox = new TextBox();
TextBox emailBox = new TextBox();
TextBox phoneBox = new TextBox();
public editContacts()
{
InitializeComponent();
}
private void editContacts_Load(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.ID = idBox.Text;
Label idLabel = new Label();
idLabel.Text = "ID: ";
idLabel.Size = new Size(80, 30);
System.Drawing.Point idLabelLocation = new System.Drawing.Point(10, 15);
idLabel.Location = idLabelLocation;
this.Controls.Add(idLabel);
idBox.Name = "ID";
idBox.Size = new Size(250, 200);
System.Drawing.Point idBoxLocation = new System.Drawing.Point(100, 15);
idBox.Location = idBoxLocation;
this.Controls.Add(idBox);
Button show = new Button();
show.Text = "SHOW";
show.Size = new Size(75, 23);
System.Drawing.Point showLocation = new System.Drawing.Point(380, 13);
showButton.Location = showLocation;
this.Controls.Add(show);
show.Click += new System.EventHandler(this.show_Click);
contact.find(contact);
}
private void show_Click(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.FirstName = firstNameBox.Text;
contact.LastName = lastNameBox.Text;
contact.Postcode = postcodeBox.Text;
contact.Email = emailBox.Text;
contact.Phone = phoneBox.Text;
Console.WriteLine("Contact: " + contact);
Label firstNameLabel = new Label();
firstNameLabel.Text = "First Name: ";
firstNameLabel.Size = new Size(80, 30);
System.Drawing.Point firstNameLabelLocation = new System.Drawing.Point(10, 45);
firstNameLabel.Location = firstNameLabelLocation;
this.Controls.Add(firstNameLabel);
firstNameBox.Text = contact.FirstName;
firstNameBox.Size = new Size(250, 200);
System.Drawing.Point firstNameBoxLocation = new System.Drawing.Point(100, 45);
firstNameBox.Location = firstNameBoxLocation;
this.Controls.Add(firstNameBox);
Button edit = new Button();
edit.Text = "Edit";
edit.Size = new Size(250, 50);
System.Drawing.Point editLocation = new System.Drawing.Point(40, 200);
edit.Location = editLocation;
this.Controls.Add(edit);
edit.Click += new System.EventHandler(this.edit_Click);
}
private void edit_Click(object sender, EventArgs e)
{
Contact contact = new Contact();
contact.ID = idBox.Text;
contact.FirstName = firstNameBox.Text;
contact.LastName = lastNameBox.Text;
contact.Postcode = postcodeBox.Text;
contact.Email = emailBox.Text;
contact.Phone = phoneBox.Text;
contact.editContacts(contact);
}
}
}
I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}
I have a form that has a ComboBox that has to display names and the when the name is select is has to show the different values from my mysql database in different textboxes.
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 MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Required_Attributes : Form
{
public Required_Attributes()
{
InitializeComponent();
}
private void cb_Talents_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = Mypass;";
string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='" + cb_Talents.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string description = myReader.GetString("Description");
string strength = myReader.GetInt32("R_Str").ToString();
string weaponskill = myReader.GetInt32("R_WS").ToString();
string ballisticskill = myReader.GetInt32("R_BS").ToString();
string fellowship = myReader.GetInt32("R_Fel").ToString();
string perception = myReader.GetInt32("R_Per").ToString();
string intelligence = myReader.GetInt32("R_Int").ToString();
string agility = myReader.GetInt32("R_Agi").ToString();
string willpower = myReader.GetInt32("R_WP").ToString();
string toughness = myReader.GetInt32("R_Tough").ToString();
string talentrequired = myReader.GetString("Talent_required");
string skillrequired = myReader.GetString("Skill_required");
string classrequired = myReader.GetString("Class_required");
TextDescription.Text = description;
TextStrengh.Text = strength;
TextWeaponskill.Text = weaponskill;
TextBallisticskill.Text = ballisticskill;
TextFellowship.Text = fellowship;
TextPerception.Text = perception;
TextIntelligence.Text = intelligence;
TextAgility.Text = agility;
TextWillpower.Text = willpower;
TextToughness.Text = toughness;
TextTalent.Text = talentrequired;
TextSkill.Text = skillrequired;
TextClass.Text = classrequired;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
}
}
However when i open the form and press the ComboBox, nothing happens, and nothing is shown, no syntax error occurs, what is wrong with the code?
UPDATE even if i change the code to:
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 MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Talents : Form
{
public Talents()
{
InitializeComponent();
}
private void cb_Talents_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Test");
//string constring = "datasource = localhost; port = 3306; username = root; password = Lorena89;";
//string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='" + cb_Talents.Text + "' ;";
//MySqlConnection conDataBase = new MySqlConnection(constring);
//MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
//MySqlDataReader myReader;
//try
//{
// conDataBase.Open();
// myReader = cmdDataBase.ExecuteReader();
// while (myReader.Read())
// {
// string description = myReader.GetString("Description");
// string strength = myReader.GetInt32("R_Str").ToString();
// string weaponskill = myReader.GetInt32("R_WS").ToString();
// string ballisticskill = myReader.GetInt32("R_BS").ToString();
// string fellowship = myReader.GetInt32("R_Fel").ToString();
// string perception = myReader.GetInt32("R_Per").ToString();
// string intelligence = myReader.GetInt32("R_Int").ToString();
// string agility = myReader.GetInt32("R_Agi").ToString();
// string willpower = myReader.GetInt32("R_WP").ToString();
// string toughness = myReader.GetInt32("R_Tough").ToString();
// string talentrequired = myReader.GetString("Talent_required");
// string skillrequired = myReader.GetString("Skill_required");
// string classrequired = myReader.GetString("Class_required");
// TextDescription.Text = description;
// TextStrengh.Text = strength;
// TextWeaponskill.Text = weaponskill;
// TextBallisticskill.Text = ballisticskill;
// TextFellowship.Text = fellowship;
// TextPerception.Text = perception;
// TextIntelligence.Text = intelligence;
// TextAgility.Text = agility;
// TextWillpower.Text = willpower;
// TextToughness.Text = toughness;
// TextTalent.Text = talentrequired;
// TextSkill.Text = skillrequired;
// TextClass.Text = classrequired;
// }
//}
// catch (Exception ex)
// {
// MessageBox.Show("Error: \r\n" + ex);
// }
}
private void Talents_Load(object sender, EventArgs e)
{
}
}
}
Nothing happens, the combobox is never fired up, how can i make it work.
I would set a static value that you know exists in the database inside the query and see if it returns anything. This will tell you if your query is incorrect.
string Query = "SELECT * FROM dark_heresy.talents WHERE TalentName='This.Guy';";
As per your second question, you can create static global variables inside your Required_Attributes form like:
public static string username;
public static string password;
And on the closing event of your login page, set the variables' values like:
private void Authenticate_Closing(object sender, FormClosingEventArgs e)
{
Required_Attributes.username = username.text;
Required_Attributes.password = password.text;
}
Your connection string would look like this:
string constring = "datasource = localhost; port = 3306; username =" + username + "; password = " + password + ";";
So I've been working on learning LINQ, and I think I'm doing this correctly, but when I spit out the value of the DropDownList's DataValueField property, it comes back as the string "mId" rather than the actual value (the menu_id). Even more strange, the DataTextField is being populated correctly, using the same syntax. Anyone have any ideas?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
List<RobDAL.Menu.menuObj> menuInfo = new List<RobDAL.Menu.menuObj>();
menuInfo = RobDAL.Menu.GetMenuText();
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
menu.DataValueField = "mId";
menu.DataTextField = "Text";
menu.DataBind();
}
Here's my Menu class:
public class Menu
{
public static int GetMainMenuByContentId(int contentid)
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
Content myContent = new Content();
int menuid;
string queryString = "SELECT menu_id FROM menu_to_item_tbl where content_id = " + contentid + ";";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
try
{
menuid = (int)command.ExecuteScalar();
}
finally
{
// Always call Close when done reading.
connection.Close();
}
return menuid;
}
}
public static List<menuObj> GetMenuText()
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
List<menuObj> allMenus = new List<menuObj>();
string queryString = "SELECT DISTINCT menu_id, menu_title FROM menu_to_item_tbl;";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
menuObj myMenu = new menuObj();
myMenu.menuId = Convert.ToInt16(reader[0]);
myMenu.menuText = reader[1].ToString();
allMenus.Add(myMenu);
}
}
finally
{
reader.Close();
}
return allMenus;
}
}
public class menuObj
{
public string menuText { get; set; }
public int menuId { get; set; }
}
}
Thanks!
Change
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
to
menu.DataSource = (from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId }).ToList();;
That is because you have assigned a string to the DataValue property of your drop down list.
menu.DataValueField = "mId".
You might also want to check to see what your linq query is returning for mId.