error while deleting row in gridview via 3 tier - c#

Object reference not set to an instance of an object.
This is the error which i m getting while i trying to delete .. row from my grid view
this is in .. page_ load
gvDetails.DataSource =myBl.DeleteAllCountry(int.Parse(gvDetails.SelectedRow.ToString()));
on data access layer
public DataTable DeleteCountry(int country_id)
{
DataTable dltcontry = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=a8-pc\sqlexpress;Integrated Security=True");
SqlDataAdapter da;
try
{
SqlCommand cmd = new SqlCommand();
cmd.connection= con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_DeleteCountry";
con.Open();
da = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("country_id", #country_id);
cmd.ExecuteNonQuery();
da.Fill(dltcontry);
con.Close();
}
and in business layer the code is like
public DataTable DeleteAllCountry(int country_id)
{
return mydtLayer.DeleteCountry(country_id);
}

First thing to correct, you need to set connection to your command
cmd.Connection =con;
or in the constructor as below
SqlCommand command = new SqlCommand(
queryString, connection);
Another problem is you try to convert selected gvDetails.SelectedRow to int value
check gvDetails.selectedRows.Count before you get value of selected row
if you have selection you can then get cell valu of your country_id column as below
gvDetails.SelectedRow.cells("country_id").Text
now you can convert this to a int value by using int.TryParse and if it is success send to your BL function to delete the record

Related

DataGridView does not show SOME data

I created an app for inserting specific data into database and it works fine.
However, when i try to view that data, DataGridView shows just some of those fields.
I stucked here. I tried to delete DataGridView and write code again, but it didn't helped.
private void displayData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\Documents\DataB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM dbo.Users ";
cmd.ExecuteNonQuery();
DataGrid.Update();
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataGrid.DataSource = dt;
conn.Close();
}
I expected completely filled DataGridView, but some fields are empty.
I can see name, username, date of birth, than 5 empty cells, then again i can see salary, education and so on..

System.Data.SqlClient.SqlException: 'Invalid column name 'music'.'

I want to display a category (service) based on menu item value, so when the user clicks on music item for example it should fill the repeater from database table (ServiceP) where the name of the service = to the menu item value.
I tried this code, but I get an error
System.Data.SqlClient.SqlException: 'Invalid column name 'music'
This is the code when users clicks a menu item
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\TOSHIBA\Documents\PartyZone.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from ServiceP where
ServiceName = "+e.Item.Value.ToString() ;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
conn.Close();
}
Assuming you actually have:
cmd.CommandText = "select*from ServiceP where ServiceName="+e.Item.Value.ToString() ;
and e.Item.Value is "music", then what you need here is a parameter to hold the value to search for, i.e.
cmd.CommandText = "select*from ServiceP where ServiceName=#value";
cmd.Parameters.AddWithValue("#value", e.Item.Value.ToString());
Note that you can also throw away the cmd.ExecuteNonQuery(); - that does nothing useful here, and means you do the work twice.

Iterating through List of Query Parameters and binding results to Gridview using DataReader and Datatable

I have a list of query parameters(selected items from checklistbox). I need to pass each parameter to a query(sql server select statement) and bind results to grid view. I am trying to add rows to datatable using datareader. Can some one please provide sample code base on how to code this requirement?
Just decalre the DataTable in global level earlier we were creating a new Data Table and loding the GridView now it will add new rows to Datatable and add to grid view
DataTable dt = new DataTable();
private void BindGrid()
{
string constring = #"Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
con.Close();
}
}
}

Insert and restore and search in combox?

Salam Alekom .
I have comboBox filling it from database as
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand scm = new SqlCommand();
scm.Connection = con;
scm.CommandText = "select * from com";
SqlDataAdapter adpt = new SqlDataAdapter(scm);
DataTable dt = new DataTable();
adpt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = dt.Columns["com_name"].ToString();
comboBox1.ValueMember = dt.Columns["com_id"].ToString();
Where filling with all data that store in the table from database.
This comboBox use also to insert to another table in database
This also poses no problem
The problem when making search in table to get some data. I need to get the text value that store in table and equal to text value of comboBox and sort it in position 0 of this comboBox
I made the search no problem but what property or method that allow me to put the value in position 0 with out affecting the other values that be in combobox
SqlConnection con = new SqlConnection(strcon);
con.Open();
using(SqlCommand scm2 = new SqlCommand())
{
scm2 .Connection = con;
scm2.CommandType = CommandType.StoredProcedure;
scm2 .CommandText = "SP_retrieve_data";
scm2.Parameters.AddWithValue ("#id", textBox1.Text);
SqlDataReader dr = scm2.ExecuteReader();
while (dr.Read())
{
comboBox1. = dr["com_name"].ToString();//what code accept the value
}
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

Categories