how to populate textbox with new Row ID in windows form - c#

I'm creating a windows form and currently in the process of creating the "create member" form.
Now i wish to show to the user inputting data what the new members ID will be. So i thought of trying to show the new row ID within a text box. So if we take the example below, when the form loads, the new member ID should be shown in the textbox
I've tried to attempt it below but having difficulty getting the result from the sqlCommand. Or maybe im going the wrong way around doing it ha
Can anyone see how i can apply the id upon load?
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT * FROM Users WHERE UserID=(SELECT MAX(UserID) FROM Users", connection))
{
//cmd.Parameters.Add("#MYVALUE", SqlDbType.VarChar).Value = comboBox1.Text;
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = // result from the SQLCommand but i dont know how to get it

You can access current row cells by indexing DataReader with columns names, like this txtMemberId.Text = thisReader["UserID"]; //here you should do increment. But honestly, generating Id in select max(id) + 1 manner is odd, GUIDs nad Autoinc integer is more commonly used in our days.
Your MAX+1 should looks like:
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT (COALESCE(MAX(UserID), 0) + 1) as UserID FROM Users", connection))
{
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = re["UserID"].ToString();

remove your autoinc id column and add a guid id col instead. then you can generate the Id on the client with Guid.NewGuid().ToString()

Assuming your ID column is being generated by the database (auto increment, etc...) just get the ID when you create the record.
var cmd = new SqlCommand("INSERT INTO User(FirstName) VALUES('bob')");
var id = (int) cmd.ExecuteScalar();
txtMemberId.Text = id.ToString();

Related

Get list of IDs from Access Database using OleDbDataReader

Using a Microsoft Access database for a Web App Quiz Manager, I have table with a ID column that has a list of IDs which looks something like this:
ID Answer QuesDescription QuesAnswer QuestionNum
1 1 Example Example 1
3 3 Example Example 2
4 4 Example Example 3
6 1 Example Example 4
Using the query SELECT ID FROM (QuizName) with OleDbCommand I managed to get the ID values from the database and stored into OleDbDataReader reader. But i don't know how to get the ID values from the reader and store them as a String List. Does anyone know how to do this?
I've tried using stuff like
public List<string> GetIDValueFromQuestionNumber(string quizNumber)
{
try
{
string strSQL = string.Concat("SELECT count(ID) as RowCount FROM ", quizNumber);
List<string> resourceNames = new List<string>();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
int rowCount = (int)reader["RowCount"];
strSQL = string.Concat("SELECT ID FROM ", quizNumber);
command = new OleDbCommand(strSQL, connection);
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
resourceNames.Add(" " + reader.GetString(0));
}
}
connection.Close();
for (int count = 0; count < rowCount; count++)
{
int value = (int)reader.GetValue(count);
resourceNames.Add(value.ToString());
}
}
return resourceNames;
}
catch (Exception e)
{
return null;
}
}
But to no luck.
I should note that these tables can vary in depth.
I suggest this approach.
Say a form - DataGridView to display our data.
And say a listbox to display the list of id that you build up into that List
So, this form:
And the button click code:
private void button1_Click(object sender, EventArgs e)
{
// load up our data list with Hotels
string strSQL =
#"SELECT ID, FirstName, LastName, City, HotelName
FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
dataGridView1.DataSource = rstData;
// now build up a list of id in to string colleciton
List<string> MyIDList = new List<string>();
foreach (DataRow MyOneRow in rstData.Rows)
{
MyIDList.Add(MyOneRow["ID"].ToString());
}
// Lets set the id list to a listbox
listBox1.DataSource = MyIDList;
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And now we get/see this:
So, pull the table. Display it, do whatever.
Then use the SAME table, and simple loop each row, grab the ID and add to your list.
And of course, one would probably hide the "id" in the above list (just add the columns using edit columns - only add the ones you want). You can still get/grab/use ANY column from the data source - it not a requirement to display such columns.

SQL query based on combobox selection

I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you
I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.

How to check if the primary key exists in my database from a textbox (windows form), c#

I have a textbox and a button in a windows form application.
I want to check if the primary key (persId) exists in my sql database/dataset (made with Visual studio) when I enter a number in the textbox and press the button. I dont know how to compare the text with persId from the database.
If the persId exists I want to fill two textboxes in a new form and show the persId and persName.
I am new to programming in C# so I have probably missed something. I looked at how to check if value exists in database from textbox c# but could not find an answer.
Thanks in advance!
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persId FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
if (textBox1.Text = myCommand ) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First, use the using-statement for everything implementing IDisposable like the connection to dispose unmanaged resources and to close the connection, even in case of an error.
Then you have to open the connection and to use ExecuteReader to get a datareader to check if there's at least one record with that ID, you can use reader.HasRows. You also have to select the persName if you want it as mentioned.
using(var conn = new SqlConnection())
using(var myCommand = new SqlCommand("SELECT persId, persName FROM Customers WHERE persId = #persId", conn))
{
myCommand.Parameters.AddWithValue("#persId", persId);
conn.Open();
using(var rd = myCommand.ExecuteReader())
{
bool personExists = rd.HasRows;
if(personExists)
{
// advance the reader to the first record, presuming there is only one, otherwise use a loop while(rd.Read)
rd.Read();
string persName = rd.GetString(1); // second field
// ...
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
}
You can also use ExecuteScalar
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persName FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
object personName = myCommand.ExecuteScalar();
if(!string.IsNullOrEmpty(personName.ToString()))
//if (textBox1.Text = myCommand) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
textBox2.Text = personName.ToString();
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First you have to Execute the command.
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
// ... if it has rows then you know it match
}
else
{
// ... data doesn't exists
}
Then you can compare the result.

Add data to a table from database

I am new to .net and C# and I want to perform update/delete. I am using e template which has a table. I want to get data from database and display in that table and then perform update.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlDataReader rd;
SqlCommand comand = new SqlCommand();
//open connection with database
connection.Open();
//query to select all users with the given username
comand.CommandText = "select * from artikulli ";
rd = comand.ExecuteReader();
if(rd.HasRows )
{
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
}
}
connection.Close();
}
Row1 is the id of table row. I know that this is not the best way and it doesn't work.
I get this error:
CS0103: The name 'Row1' does not exist in the current context
My table row Row1 is declared as below:
<td id="Row1" style="width: 73px"> </td>
It's apparent, as you've admitted, you are new to C#, so there are a number of things to point out, as have been addressed in the comments.
HTML elements are not going to be visible to the code-behind without the runat="server" attribute. (This attribute is required for ASP elements.)
As marc_s pointed out, your database communication would currently produce a run-time error, as the SqlCommand was not given a connection.
At some point you must really familiarize yourself with the using statement.
To correct your code-behind, it should be more like the following:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
//open connection with database
connection.Open();
//query to select all users with the given username
command.CommandText = "select * from artikulli ";
List<object> users = new List<object>();
using (SqlDataReader rd = command.ExecuteReader())
{
if (rd.HasRows)
{
while (rd.Read())
{
users.Add(rd[0].ToString());
}
}
}
myGridView.DataSource = users;
myGridView.DataBind();
}
}
}
Where myGridView is an instance of a GridView created in the aspx page. The list users should be a list of whatever class you want to create to show user data, which will determine how your GridView instance will be formatted.
Just to get you to the point where you can see your database query working at all you can instead do the following from your query result (though I definitely recommend implementing the GridView eventually):
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (SqlDataReader rd = command.ExecuteReader())
{
if (rd.HasRows)
{
while (rd.Read())
{
sb.Append(rd[0].ToString());
sb.Append("<br />");
}
}
}
Row1.InnerHtml = sb.ToString();
And you will have to change your Row1 to
<td id="Row1" style="width: 73px" runat="server"> </td>
Per the error, you'll need to bring your Row1 variable into scope
TableRow Row1 = new TableRow();
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
Table1.Rows.Add(Row1);
}

Displaying the values of listview in textboxes

I'm creating an application in Visual Studio 2010 C# and MySQL where the user can add, edit, view an employee. I already done with adding and viewing part. However I'm little confused in editing. I have this listView in my form where it displays all the employee added to the database. What I want is that whenever the user will select an employee and click edit button I want the values saved in the database to show in the corresponding textboxes below the listView. Can someone give me any idea how to do this? Please
Screenshot:
Code for listView:
private void getEmployee()
{
listViewEmployee.Items.Clear();
string cmd = "select employee_number, employee_lastname, employee_firstname, employee_middlename, employee_position, employee_datehired from employee";
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
foreach (DataRow row in tbl.Rows)
{
ListViewItem lv = new ListViewItem(row[0].ToString());
lv.SubItems.Add(row[1].ToString() + ", " + row[2].ToString() + " " + row[3].ToString());
lv.SubItems.Add(row[4].ToString());
lv.SubItems.Add(row[5].ToString());
listViewEmployee.Items.Add(lv);
}
}
private void textBoxSearchEmployee_TextChanged(object sender, EventArgs e)
{
string cmd = "SELECT employee_number, employee_lastname, employee_firstname, employee_middlename, employee_position, employee_datehired FROM employee where employee_lastname Like '" + textBoxSearchEmployee.Text + "%'";
listViewEmployee.Items.Clear();
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
foreach (DataRow row in tbl.Rows)
{
ListViewItem lv = new ListViewItem(row[0].ToString());
lv.SubItems.Add(row[1].ToString() + ", " + row[2].ToString() + " " + row[3].ToString());
lv.SubItems.Add(row[4].ToString());
lv.SubItems.Add(row[5].ToString());
listViewEmployee.Items.Add(lv);
}
}
It seems to me you are able to populate the listView only.
A few pointers:
1) The way you're writing your SQL statement now is prone to SQL Injection. Use parameters in your SQL commands instead of directly concatenating the variables to your query. See this question for an example on how to do it.
2) Depending on where your other relevant data is located (i.e. if your database is normalized), you might have to do a join in your query.
string sqlQuery = "SELECT * FROM employee
JOIN other_employee_data_table on other_employee_data_table.employeeID = employee.ID
WHERE employee.employee_lastname LIKE #employee_lastname +'%'"
But if your employee table contains all the data, then no need to do a join. Just get all the relevant information from that table.
3) Once you got all the information you need, it's just a matter of reading those data and assigning them to their respective fields.
Pseudo Code:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = sqlQuery;
command.CommandType = System.Data.CommandType.Text;
// add parameters in this line
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// iterate in each row
for (int i = 0; i < reader.FieldCount; i++)
{
// iterate each column using reader.GetValue(i)
}
}
}
}
When the user presses the "edit" button...
Retrieve the selected employee
Use a SELECT to get the selected employee's information
Populate the text boxes with the selected employee's information
For example,
String employee = listViewEmployee.Text;
String cmd = "SELECT * FROM employee WHERE employee_lastname='" + employee + "'";
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
txtLastName.Text = tbl.Rows[0][0];
// ...
// etc.
Note: It's a bad idea to concatenate values into a SQL query because if the values are malicious, a different query could be executed. For example, if employee had the value of x' OR '1'='1; DROP TABLE employee; -- or something along those lines, then the employee table could be dropped. The way around this is using Stored Procedures or parameterized queries.

Categories

Resources