Data in textbox doesn't exists in the database then display message - c#

I am working on a C# windows forms application. It has a form with the following fields:
textboxRegistrationID,
TextboxDate,
TextboxName,
TextBoxGender and
TextBoxContactNumber
with three buttons GetData, Save and Exit.
In the database I am having a table with the name info with five fields:
RegistrationID,
Date,
Name,
Gender and ContactNumber respectively.
When I save the data, it saves respectively and when I try to get the data from the database using RegistrationID, it will give the data if the RegistrationID exists. If it doesn't exist, it throws an error, saying column doesn't exists.
Now what I want is, instead of the Error, I want a message to be displayed saying Registration Number Doesn't Exists.
How can I achieve this? Please help me.

As you mention your code according to that you can count rows of datatable
here is the code
if(dt.Rows.Count > 0)
{
//display your data
}
else
{
// show your message here
}
if you have any problem then let me know.
Note:- Here dt is your DataTable variable

When you fetch the data from the database, say in a DataSet ds; check following things
ds != null;
ds.Tables.Count > 0;
ds.Tables[0] != null;
ds.Tables[0].Rows.Count > 0;
If any of the above condition turns out to be true; display
MessageBox.Show("Record doesn't exist!!!")
Else, display the results
Update
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * from Info where RegistrationID = '" + RegistrationID.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt != null && dt.Rows.Count() > 0)
{
RegistrationID.Text = dt.Rows[0][0].ToString();
Date.Text = dt.Rows[0][1].ToString();
Name.Text = dt.Rows[0][2].ToString();
Gender.Text = dt.Rows[0][3].ToString();
ContactNumber.Text = dt.Rows[0][4].ToString();
}
else
{
MessageBox.Show("Data does not exist!!!");
}
}

Related

How to display Access data in a DataTable in C#?

I'm new to C#. I'm having a difficult time displaying my Access data in a DataTable. Here is the code:
try
{
reader.Read();
for (int i = 0; i < 16; i++)
{
if (selectedCourse == reader["CourseName"].ToString())
{
match = true;
}
else
{
match = false;
}
}
if (match == true)
{
tabControl.SelectedTab = tabPage1; // opens results page
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\...454_Database.accdb";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select c.PeriodID, c.CourseName, c.Teacher, t.Room"
+ "FROM Courses c JOIN Teacher t ON t.TeacherID = c.TeacherID"
+ "WHERE [CourseName] ='" + cboxClass.Text + "'", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataTblResults.DataSource = results;
I can tell the data is being compared to the db and it correctly determines if the query has results or not. However, when there are results, they do not get displayed on the data table. Is it because it doesn't know which columns correspond to the columns in the data table?
Thanks in advance!
How is your datagrid configured?
Try setting: (before setting the DataSource)
dataTblResults.AutoGenerateColumns = true;
dataTblResults.DockStyle.Fill = DockStyle.Fill;
Try using a Dataset first. Then turn it to a datatable
DataSet ds = new DataSet();
adapter.fill(ds)
if (ds.Tables[0].Rows.Count >= 1)
{
results = ds.Tables[0];
}
dataTblResults.DataSource = results;
I dont think this is what you are looking for but maybe it'll bring you closer to the answer

GridView issue with more than 1000 records

I'm having some performance issues when I return a record set with more than 1,000 records.
Sometimes the records are in upwards of 2,100 but can be as low as 10.
I have some bulk actions that I take on all the records by selecting them.
However, when the number is low, the Gridview is fine. When the record count is greater than 500 I see performance issues on the page.
What I want to happen is: if there are more than 500 records, DO NOT DISPLAY THE GRID, instead show a download button that exports to CSV or do other control things on the page.
My issue:
Even if i tell it not to display the grid and instead display a message and a button, the performance is still slow.
Below is my C# code for populating the GridView. Some stuff has been removed that are unimportant and to help with readability.
How can I adjust my C# code for better performance?
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectString"].ToString());
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SomeProcedure";
cmd.Parameters.Add(SearchParam);
try {
DataTable GridData = new DataTable();
conn.Open();
using(SqlDataAdapter Sqlda = new SqlDataAdapter(cmd)) {
Sqlda.Fill(GridData);
}
if (GridData.Rows.Count == 0) {
lblSearchMsg.Text = "No Fee Records are in the Queue at this time.";
} else {
if (GridData.Rows.Count > 500) {
lblSearchMsg.Text = "More than " + gridLimit.ToString() + " records returned.";
//Show the download button
} else {
//Persist the table in the Session object. (for sorting)
Session["GridData"] = GridData;
lblRowCount.Text = "Count: " + GridData.Rows.Count.ToString();
myGridView.DataSource = GridData;
myGridView.DataBind();
myGridView.Visible = true;
}
}
} catch (Exception ex) {
//Do the error stuff
} finally {
if (conn != null) {
conn.Close();
}
}
Create a separate procedure that returns only the row count.
Check that value not the row count of a fully retrieved data set then retrieve the full data set as needed.
Keep in mind you can use the same connection to do both retrievals, no need to close the connection between calls.
if you determine you need to fill a gridview and there is no need to edit the data you can read into the DataTable without the use of an adapter. Here is the basic idea modify with using statements or try/catch as you prefer:
conn = new SqlConnection(connString);
string query = "SELECT * FROM ....";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();

How to get saved date value from Sql Server in dateTimePicker Control in Windows Application

I have a simple registration table of employee having column Name, Number, Email, DOB, JoinDate.
I want to populate this value in the form in respective controls, i.e Name value goes in textbox and DOB value goes in dateTimePicker control and dateTimePicker automatically select the date which is coming from DB.
I do the logics for textboxes but not have a solution for dateTimePicker Control.
I am attaching some code for reference.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCN"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Select * from EmpRegister", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
txtName.Text = dt.Rows[0]["EmpName"].ToString();
txtPassword.Text = dt.Rows[0]["Password"].ToString();
txtPassword.Enabled = false;
txtUserName.Text = dt.Rows[0]["UserName"].ToString();
txtDesignation.Text = dt.Rows[0]["EmpDesignation"].ToString();
txtMobileNumber.Text = dt.Rows[0]["Empnumber"].ToString();
txtEmailId.Text = dt.Rows[0]["EmpEmail"].ToString();
bindRole();
comboboxRole.SelectedValue = dt.Rows[0]["EmpRole"].ToString();
dateTimePickerJoinDate.Value = Convert.ToDateTime("JoinDate");
dateTimePickerDOB.Value = dt.Rows[0][Convert.ToDateTime(DOB)].ToString();
dateTimePickerJoinDate.Value = dt.Rows[0][Convert.ToDateTime(JoinDate)].ToString();
//string Gender = null;
//if (radioButtonMale.Checked)
//{
// Gender = "Male";
//}
//else
//{
// Gender = "Female";
//}
//radioButtonMale.Checked = dt.Rows[0]["Gender"].ToString();
}
else
{
MessageBox.Show("No Data in dt");
}
}
Please tell me how can i get the values of date in the datetimepicker control.
I am working on windows application.
Thanks in advance
Ankush,
I noticed you're trying to set dateTimePickerJoinDate in two places in different ways. The first way looks like you're trying to convert the string "JoinDate" to a date, which should throw an error.
Have you tried this syntax:
dateTimePickerJoinDate.Value = dt.Rows[0]["JoinDate"].ToString();
-- or
dateTimePickerJoinDate.Value = Convert.ToDateTime(dt.Rows[0]["JoinDate"]);
--Jim
It is also possible to pass the date time from your sql database then convert that string to Date Time:
string sqlDate = dt.Rows[0]["JoinDate"].ToString();
dateTimePIckerJoinDate.Value = Convert.ToDateTime(sqlDate);

INSERTED data via SQL command does not show correctly in comboBox1

I have a problem where after I insert data into my SQL Lite database the combobox1 doesnt refresh to show the data correctly. After I insert my data I simply call the following method:
void fillcomboBox1()
{
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed)
{
m_dbConnection.Open();
}
SQLiteDataAdapter da = new SQLiteDataAdapter("select * from rdpdirectory order by company asc", m_dbConnection);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Company"]);
}
m_dbConnection.Close();
}
My insert code looks like this:
void InsertConnectionDetails()
{
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed)
{
m_dbConnection.Open();
}
string sql = #"insert into rdpdirectory (company, server, username, password)
values (#company, #server, #username,#password)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("#company", txtCompany.Text);
command.Parameters.AddWithValue("#server", txtServer.Text);
command.Parameters.AddWithValue("#username", txtUserName.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
command.ExecuteNonQuery();
m_dbConnection.Close();
fillcomboBox1();
comboBox1.Refresh();
MessageBox.Show("Done");
}
I thought the idea was to fill the datatable again and the combobox should show the values? The problem specifically is that i see duplicates of the same value but when i restart the app, the correctly inserted values show.
Problem : You are adding the Items into Combobox everytime you call the fillcomboBox1() method.
so if you call the fillcomboBox1() method two times ComboBox will surley will have the duplicate items as you are adding items twice.
Solution : You need to clear the Items from ComboBox before adding Items.
You can use comboBox1.Items.Clear() method to clear all existing items from the Combobox before adding items into it.
Add the following statement into fillcomboBox1() method.
comboBox1.Items.Clear();
Complete Code:
void fillcomboBox1()
{
comboBox1.Items.Clear();// <---Add this statement
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed)
{
m_dbConnection.Open();
}
SQLiteDataAdapter da = new SQLiteDataAdapter("select * from rdpdirectory order by company asc", m_dbConnection);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Company"]);
}
m_dbConnection.Close();
}
bind the comboBox1 as below
void fillcomboBox1()
{
// your code .....
da.Fill(dt);
comboBox1.DataSource = dt; // set DataSource as your DataTable
comboBox1.DisplayMember = "Company"; // you only need to set the display column name
m_dbConnection.Close();
}
otherwise you need to clear the items befor adding new items

How to check if a field in a table already exists?

my question is very simple:
i have a SQL Table with a column name 'lastname' with fields lastname1,lastname2,lastname3...
In my c# code, i have a method that inserts in the table a row only if the field of the column lastname is not present in the table. This method in input has lastname, so for my INSERT is a parameter.
How can i compare and conseguently check if the field lastname is already in table?
Thanks
You should always use unique constraints in the table if a field must be unique. On that way you prevent duplicates always, even if the input was directly from SSMS or another application.
Then the easiest would be to handle the sql-exception that is raised according to it's number.
....
try
{
int inserted = cmd.ExecuteNonQuery();
} catch (SqlException ex)
{
if (ex.Number == 2601)
{
// show meaningful error message
MessageBox.Show("Cannot insert duplicate key row in object");
}
else
throw;
}
....
This SQL will insert a new record only if the value isn't already in the table:
INSERT INTO Your_Table ( LastName )
SELECT #NewLastName
WHERE NOT EXISTS( SELECT * FROM Your_Table WHERE LastName = #NewLastName )
There are two option one is from sql side another way is from code behind.
unfortunately you can't change your sql code i agree with #David.
from code behind you have to do something like this.
First you have to select all the data from your table and check that data. something like this.
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //Your connection string"
cmd.CommandText = "Select * from table1"; // your query
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
int count=0;
for (int i = 0; i > dt.Rows.Count; i++)
{
if (Convert.ToString(dt.Rows[i]["LastName"]) == Lastname)
{
count++;
}
}
if (count > 0)
{
//insert code for data
}
else
{
var script = "alert('"+ Lastname + "already exist.');";
ClientScript.RegisterStartupScript(typeof(Page), "Alert", script, true);
// or you can use here your Update statement
}
May this will help you and you can understand.

Categories

Resources