Whenever I click on a name in EmployeeRank1 List listbox I want to get in the EmployeeRank1Information listbox associated data from the table for it. However, I get an exception instead. Screenshots and code used provided below.
Table
WPF Window
Exception
Code I have used
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1InformationTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1InformationTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1Information.DisplayMemberPath = "Salary";
employeeRank1Information.DisplayMemberPath = "Position";
employeeRank1Information.DisplayMemberPath = "Responsibility";
employeeRank1Information.DisplayMemberPath = "Age";
employeeRank1Information.DisplayMemberPath = "YearsInCompany";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.ToString());
}
}
}
You could just pass Id into the query, as that is the primary key of Employee
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue == null) // less nesting to flip the condition
return;
try
{
// only select the columns you need
const string query = #"
select
Id,
Name,
Salary,
Position,
Responsibility,
Age,
YearsInCompany
from EmployeeRank1 e
where e.Id = #id
";
// always use a new connection and dispose it
using (SqlConnection sqlConnection = new SqlConnection(yourConnectionString))
// Create an SqlCommand and connect to the database
using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
{
// always specify parameter type (and length for strings)
sqlCommand.Parameters.Add("#id", SqlDbType.Int).Value = ((DataRow)employeeRank1List.SelectedValue)["Id"];
// how do you get the Id column??
DataTable employeeRank1InformationTable = new DataTable();
conn.Open();
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
employeeRank1InformationTable.Load(reader);
}
} // close connection as quick as you can
// you can only set one column to display
employeeRank1Information.DisplayMemberPath = "Name";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.Message);
}
}
You have declared where conditions for these without value
AND Salary = #salary AND
Responsibility = #responsibility AND
Position = #position AND
Age = #age AND
YearsInCompany = #yearsInCompany
You need to Fille them before executing the query
sqlCommand.Parameters.AddWithValue("#Salary", <VALUE FROM TABLE>);
Since you have not specified how you fill the gridview or table,
you need to get the following values yourself
Your SQL query contains 6 Conditions.
select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany.
but you have only filled one using -
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
so basically the query is equal to this when clicking on a list item
select * from EmployeeRank1 where Name = <LitsView Item>
AND Salary = UNDEFINED
AND Responsibility = UNDEFINED
AND Position = UNDEFINED
AND Age = UNDEFINED
AND YearsInCompany = UNDEFINED;
now UNDEFINED here makes it a SQL syntax error since the scalar variables are missing. to get it to work, here is a workaround for you to understand how it works-
change this line in your code
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
to this
string query = "select * from EmployeeRank1 where Id = #name";
after you try this it should work with inaccurate results. to make it work properly fill the rest of the where conditions in your SQL code
Also, use a primary/unique key to locate records instead of using #NAME
I managed to make it work by having multiple listboxes instead of one. Moreover, in the query I selected the id only, which is the primary key and then added multiple try-catch blocks in order to fill those listboxes that I had created. A screenshot of the working program, as well as the code
Program
Code
// a method that shows information for employees that are rank 1
private void ShowEmployeeRank1Information()
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1PositionTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1PositionTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1PositionList.DisplayMemberPath = "Position";
employeeRank1PositionList.SelectedValuePath = "Id";
employeeRank1PositionList.ItemsSource = employeeRank1PositionTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1AgeTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1AgeTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1AgeList.DisplayMemberPath = "Age";
employeeRank1AgeList.SelectedValuePath = "Id";
employeeRank1AgeList.ItemsSource = employeeRank1AgeTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1ResponsibilityTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1ResponsibilityTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1ResponsibilityList.DisplayMemberPath = "Responsibility";
employeeRank1ResponsibilityList.SelectedValuePath = "Id";
employeeRank1ResponsibilityList.ItemsSource = employeeRank1ResponsibilityTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1YearsInCompanyTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1YearsInCompanyTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1YearsInCompanyList.DisplayMemberPath = "YearsInCompany";
employeeRank1YearsInCompanyList.SelectedValuePath = "Id";
employeeRank1YearsInCompanyList.ItemsSource = employeeRank1YearsInCompanyTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
}
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
ShowEmployeeRank1Information();
}
}
Related
I am working on a C# windows application to populate records from SQL Server to data grid view, with dynamic checkbox facility in each row. I want to select selected rows for some purpose via checkbox of that particular row. Till now I successfully achieve my target, but I'm facing a minor issue regarding saving a checked status.
For example I want to check only those records whose Name = Max. I have a textbox in that textbox I call text change event with like Query:
try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like #Name order by Pno";
cmd.Parameters.AddWithValue("#Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
If I write Max in filter by name textbox it would return 3 records with name starts with max using like query as I mention code above. So I only check 2 records out of 3 using dynamic checkbox, till now my code runs perfectly. Now I want to check records which name starts from Ali, now when I write ali in my filter by name textbox it will return rows where name like ali , but problem comes here it will remove my previous checked records, so how I would able to save checked records for both max and ali's rows:
Code for adding dynamic checkboxes in each row
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.Name = "checkBoxColumn";
checkBoxColumn.DataPropertyName = "Report";
checkBoxColumn.HeaderText = "Report";
dataGridView1.Columns.Insert(10, checkBoxColumn);
dataGridView1.RowTemplate.Height = 100;
dataGridView1.Columns[10].Width = 50;
Images:
Image 1
Image 2
I suggest you achieve this by caching selected rows, first you should have a list of cached rows:
List<DataGridViewRow> CachedRows = new List<DataGridViewRow>();
then add event handler on cell value change like the following:
dataGridView1.CellValueChanged += view_CellValueChanged;
and the handler should check if the column changed is the checkbox and checked, should be something like the following:
try
{
if(e.ColumnIndex == indexOfCheckBoxColumn)
{
if((bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == true)
{
CachedRows.Add((DataGridViewRow)dataGridView1.Rows[e.RowIndex].Clone());
}
else if (CachedRows.Contains(dataGridView1.Rows[e.RowIndex]))//Validate if this works, if not you should associate each row with unique key like for example (id) using a dictionary
{
CachedRows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
}
catch(Exception ex)
{
}
then after the filter changes, re-add the cached rows again, so code becomes:
try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like #Name order by Pno";
cmd.Parameters.AddWithValue("#Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
//add folowing
if (CachedRows.Any())
{
dataGridView1.Rows.AddRange(CachedRows.ToArray());
CachedRows.Clear();
}
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
I want to grab data from database and display in labels based on what the user selects in the list view.
I'm going off an example that does this with two list views, but I don't know how to do it when I'm sending data to a label.
This is the list view example I'm using (my label code is below this)
private void PopulateRecipeIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = #RecipeId";
// # is a parameter
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
// whatever recipe is selected in lstRecipes box, get the id of that and pass into query above
command.Parameters.AddWithValue("#RecipeId", lstRecipes.SelectedValue);
// DataTable holds the data return from query
DataTable ingredientTable = new DataTable();
// SqlDataAdapter object adapter fills the ingredientTable DataTable object with results from query
adapter.Fill(ingredientTable);
// Display value of Name ex. salad
lstIngredients.DisplayMember = "Name";
// Id column is how we reference
lstIngredients.ValueMember = "Id";
// connect list box on form to data in recipeTable
lstIngredients.DataSource = ingredientTable;
}
}
MY CODE:
private void PopulateCourseDetails()
{
string query = "SELECT * FROM Course_Info WHERE Id = #CourseId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#CourseId", lstCourses.SelectedValue);
DataTable courseTable = new DataTable();
adapter.Fill(courseTable);
lblCourseId.Text = "Course_id";
lblCourseSection.Text = "Course_section";
lblCourseName.Text = "Course_name";
lblCourseDay.Text = "Course_day";
lblCourseStartTime.Text = "Course_start_time";
lblCourseEndTime.Text = "Course_end_time";
lblCourseProfessor.Text = "Course_professor";
lblCourseProfessorEmail.Text = "Course_professor_email";
lstCourses.ValueMember = "Id";
}
}
lblCourseId.Text = (string)courseTable.Rows[0]["Course_id"]
should work as long as you have one row in the result table
Assuming that your DataTable has now been properly populated, you now have a table with a number of rows.
First you need to pull out the first row
var row = courseTable.Rows.FirstOrDefault();
Now you've got a row with a number of columns. You can access each column by either index or column name.
lblCourseId.Text = row[0];
If you want the label to maintain it's header, you can do something like
lblCourseId.Text = "Course_id: " + row[0];
I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";
I am trying to link my c# form to a database that can hold all the data that is inserted in the form.
the other four fields are being inserted into the database correctly.
the problem that I am having is that every time a new record is created, a unique identifier needs to be generated in the last field of the SQL table.
The only way I can do this is by using a guid. But the problem is that I need the Identifier to start from 1 and increment.
I'm not sure how to do this in C# so any help provided would be excellent.
Here is my code
protected void Unnamed1_Click(object sender, EventArgs e)
{
string box1value = TextBox1.Text;
string box2value = TextBox2.Text;
string box3value = TextBox3.Text;
SqlConnection myConnection = new SqlConnection(sConnection);
string sql = "INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate, FormID, RowID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID, #RowID)";
myConnection.Open();
try
{
// create a db command objet using the sql and db connection
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
//box1value
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
cmdIns.Parameters.Add("#RowID", SqlDbType.UniqueIdentifier);
cmdIns.Parameters["#RowID"].Value = Guid.NewGuid();
// run the query
cmdIns.ExecuteNonQuery();
// end the command object
cmdIns.Dispose();
cmdIns = null;
}
catch(Exception ex)
{
Response.Write(ex);
}
myConnection.Close();
You are looking for an IDENTITY COLUMN
For Example
CREATE TABLE [dbo].[Part1Table](
[CustomerDetail] [nvarchar](50) NULL,
....
[RowID] [int] IDENTITY(1,1) NOT NULL
CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
[RowID] ASC
)ON [PRIMARY]
If you have an identity column, the job to add an increment value to every new record, is passed to the database engine.
Of course you cannot pass a value yourself for this column, but you read the value assigned by the database using the command SCOPE_IDENTITY
SELECT SCOPE_IDENTITY()
So, summarizing you could write
string sql = #"INSERT INTO Part1Table (CustomerDetails, TechnologyPartner, ResponseDate,
FormID) VALUES (#CustomerDetails, #TechnologyPartner, #ResponseDate, #FormID)";
using(SqlConnection myConnection = new SqlConnection(sConnection))
SqlCommand cmdIns = new SqlCommand(sql, myConnection);
{
try
{
myConnection.Open();
cmdIns.Parameters.Add("#CustomerDetails", SqlDbType.Char);
cmdIns.Parameters["#CustomerDetails"].Value = box1value;
//box2value
cmdIns.Parameters.Add("#TechnologyPartner", SqlDbType.Char);
cmdIns.Parameters["#TechnologyPartner"].Value = box2value;
//box3value
cmdIns.Parameters.Add("#ResponseDate", SqlDbType.DateTime);
cmdIns.Parameters["#ResponseDate"].Value = box3value;
cmdIns.Parameters.Add("#FormID", SqlDbType.Int);
cmdIns.Parameters["#FormID"].Value = 1;
// No parameter for the ROWID column.
// It will be an error to try to insert
// a value for that column
cmdIns.ExecuteNonQuery();
// Read back the value using the SAME connection used for the insert
cmdIns.Parameters.Clear();
cmdIns.CommandText = "SELECT SCOPE_IDENTITY()";
object result = cmdIns.ExecuteScalar();
int newRowID = Convert.ToInt32(result);
}
}
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.