GridView does not bind with datasource - c#

What is the problem with the following code? The GridView GridView1 does not show up on page at all.
public void display_range_mark()
{
int from = int.Parse(ddl_from_mark.SelectedValue.ToString());
int to = int.Parse(ddl_to_mark.SelectedIndex.ToString());
DataTable dt=Data.DoSomthing(string.Format("select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>='{0}' AND tn.NomreAdad<='{1}' AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars",from,to));
//DataTable data = Data.DoSomthing(string.Format("select t.Name,t.Id from tblStd t where t.DateSabt='{0}'", p.GetYear(DateTime.Now)));
GridView1.DataSource = dt;
GridView1.HeaderRow.Cells[0].Text = "نام";
GridView1.HeaderRow.Cells[1].Text = "نام خانوادگی";
GridView1.HeaderRow.Cells[2].Text = "شماره دانش آموزی";
GridView1.HeaderRow.Cells[3].Text = "درس";
GridView1.HeaderRow.Cells[4].Text = "نمره";
GridView1.DataBind();
}
I am getting this error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
The error occurs at this line:
GridView1.HeaderRow.Cells[0].Text = "نام";
By the way, the code for Data.DoSomthing is as folllows (It is located within class Database):
SqlConnection sc = new SqlConnection(#"Data Source=.;Initial Catalog=School;Integrated Security=True");
public DataTable DoSomthing(string text)
{
sc.Open();
DataTable data = new DataTable();
try
{
SqlCommand command = new SqlCommand();
command.Connection = sc;
command.CommandType = CommandType.Text;
command.CommandText = text;
SqlDataAdapter sd = new SqlDataAdapter(command);
sd.Fill(data);
if (data.Rows.Count == 0)
data = null;
}
catch (Exception ex)
{
sc.Close();
return null;
}
finally
{
if (sc.State != ConnectionState.Closed)
{
sc.Close();
}
}
return data;
}

Where is the connection object to connect to the database and fetch values ?
The way to do this:
string query="select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>=#from AND tn.NomreAdad<=#to AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars";
//Create Sqlconnection object
using(SqlConnection con = new SqlConnection(connectionstring))
{
//open the connection
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, con);
//To avoid sql injection using parameters
sda.Paramaters.AddWithValue("#from",from);
sda.Paramaters.AddWithValue("#to",to);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

Related

Don't show insert tile second insert do in localDataBace

I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}

HOW TO HANDLE ERROR SOAPEXCEPTION WAS UNHANDLED IN C#

I am trying to consume my webservice to my windows application. My webService
return datatable. Error occurs in my windows application.
here's my code:
this is my code in Web Service:
[WebMethod]
public DataTable searchCom(string compCode)
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
This is my code in Windows Application Form:
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = service.searchCom(textBox1.Text);
if(dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
textBox2.Text = row["CompanyName"].ToString();
textBox3.Text = row["balance"].ToString();
textBox4.Text = row["maintBalance"].ToString();
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
button1.Visible = false;
Back.Visible = true;
}
}
}
You should handle exception at web service level.
[WebMethod]
public DataTable searchCom(string compCode)
{
try
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw new SoapException("Exception :",
SoapException.ServerFaultCode, "SoapException", ex);
}
}
Then catch the exception at consumer end
private void button2_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
dt = service.searchCom(textBox1.Text);
if(dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
textBox2.Text = row["CompanyName"].ToString();
textBox3.Text = row["balance"].ToString();
textBox4.Text = row["maintBalance"].ToString();
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
button1.Visible = false;
Back.Visible = true;
}
}
}
catch (SoapException ex)
{
if(ex.Actor == "SoapException")
//Do something
}
}
Have you set up the WebService to run as NTLM?
WebServices, by default, run as Anonymous in IIS. But you've got your SQL Connection using Integrated security (aka, the currently logged in user). Have you set your web service to run using NTLM or something? Because unless you go out of your way during your service setup and connection, you're going to get an exception because it can't connect into the SQL database as the default IIS user.
i try changing my web-service DataTable to DataSet and it works perfectly.
just answering my own problem :P
[WebMethod]
public DataSet searchCom(string compCode)
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
conn.Open();
DataSet dt = new DataSet();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}

C# InvalidOperationException when creating a new SqlDataAdapter

I`ve written some code to establish a connection to SQL Server, then execute select procedure to take all data from my data table in SQL server, but it throw a InvalidOperationException at the command of declare a new SqlDataAdapter, please help me to fix this error.
public class dBConnect
{
//create SQLconnection variable
private SqlConnection con;
//create default constructor that passing a string to con
public dBConnect()
{
try
{
con = new SqlConnection(#"Server=Trump\SQLEXPRESS;
Database=Demo;User Id=sa;Password = stevejobs;");
}
catch(Exception exCon)
{
Console.WriteLine("Unable to connect to database: {0}", exCon);
}
}
//create Select method to Pour the data into the DataTable
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
//create a DataTable to store Data from DB
DataTable dt = new DataTable();
//create SQLCommand
SqlCommand cmd = new SqlCommand(procName, con);
//declare that cmdType is sp
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
//InvalidOperationException was thrown at here
SqlDataAdapter da = new SqlDataAdapter(cmd);
//declare that cmd is select command of da
da.SelectCommand = cmd;
//use try/catch/finally to establish a connection
try
{
con.Open();
da.Fill(dt);
}
catch(Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
finally
{
con.Close();
con.Dispose();
}
return dt;
}
}
}
You should:
cmd.CommandText = "your Stored Procedure here.";
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
Put your con.Open(); above
or
Just take a look at this steps
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
//sample stored procedure with parameter:
// "exec yourstoredProcedureName '" + param1+ "','" + param2+ "'";
cmd.CommandText = "Your Stored Procedure Here";
cmd.CommandType =CommandType.StoredProcedure;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
Cleaning up your code a bit here:
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(procName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (para != null)
cmd.Parameters.AddRange(para);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
catch (Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
return dt;
}

Error :System.NullReferenceException: Object reference not set to an instance of an object

I am trying to debug the above error. Below is my code.
private SqlConnection SQLConn(string name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return conn;
}
protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = SQLConn("Plastics");
try
{
string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (SqlException Exception)
{
// catch exception
Response.Write("An error occured");
}
finally
{
conn.Close();
}
}
I get an error on GridView1.DataSource = cmd.ExecuteReader();
What must I instantiate?
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string str = "User ID=username;Password=password;Data Source=Test";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from table_name";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt!=null)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
}

How can I return dataset perfectly from SQL?

I try to write a winform application:
I dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
Above part of codes looks unsufficient.How can I best loading dataset?
public class LoadDataset
{
public DataSet GetAllData(string sp)
{
return LoadSQL(sp);
}
private DataSet LoadSQL(string sp)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(sp, con);
DataSet ds;
try
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
finally
{
con.Dispose();
cmd.Dispose();
}
}
}
Here is a simple function I converted from VB to C# (http://www.developerfusion.com/tools/convert/vb-to-csharp/). I use this extensively.
Simple wrapper function to help return a dataset from and SQL statement via an existing connection.
This should have performance improvements over re-connected via a connection string each time. Wraps any SQL errors in to a custom format.
public System.Data.DataSet GetDataSet(string sqlStatement, System.Data.SqlClient.SqlConnection connection)
{
System.Data.DataSet functionReturnValue = default(System.Data.DataSet);
if (connection == null) {
throw new ArgumentNullException("connection");
}
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet dset = new System.Data.DataSet();
try {
// Connect to the database
if (connection.State != ConnectionState.Open) {
connection.Open();
}
if (connection.State != ConnectionState.Open) {
throw new MyCustomException("Connection currently {0} when it should be open.", connection.State));
}
// Create a command connection
cmd = new System.Data.SqlClient.SqlCommand();
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStatement;
}
//.ExecuteReader() 'Forward only Dataset
// Create a data adapter to store the inforamtion
adp = new System.Data.SqlClient.SqlDataAdapter();
dset = new DataSet();
{
adp.SelectCommand = cmd;
adp.Fill(dset, "Results");
}
// Return the resulting dataset to the calling application
functionReturnValue = dset;
}
catch (System.Data.SqlClient.SqlException objSE) {
functionReturnValue = null;
// Let the calling function known they stuffed up and give them the SQL to help out.
throw new JDDataException(System.String.Format("SQL :- {0}.", sqlStatement), objSE);
}
finally {
if ((cmd != null)) cmd = null;
if ((adp != null)) adp = null;
if ((dset != null)) dset = null;
}
return functionReturnValue;
}
public string GetSqlConnection()
{
return System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
}
public DataSet getDataSet(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
conn.Dispose();
da.Dispose();
return ds;
}

Categories