Asp.net the gridView does not show the row headers - c#

I have this problem,
when the table is empty, the GridView does not show the row headers
i use .net framework 4 and internet Explorer,Can you help me?
this is the code:
this is code
private void loadTCOR27()
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
string sql = null;
gridViewTCOR27.Visible = true;
table1.Visible = false;
string connectionString = SestanteWeb.Global.rCRVigServer.leggiStringaConnessioneSicurezzaSqlClient();
sql = "select * FROM [PUMA2_FINANZIARIAFAMILIARE].[dbo].[TCOR27]";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
// gridView1.DataSource = ds.Tables[0];
gridViewTCOR27.DataSource = ds.Tables[0];
gridViewTCOR27.DataBind();
}
catch (Exception ex)
{
}
finally
{
adapter.Dispose();
}
}

Set the property ShowHeaderWhenEmpty to true in your Gridview declaration. May be it will help you.
Here is the reference to this property.
Ref

Related

How to search data in gridview using a TextBox value with an Oracle Database

I am trying to show Oracle Data in a DataGridView in my Windows Form Application but it just returns a grey blank view. My code for this currently is:
string insertquery = "select * from Candidate where CandidateName like '"+ txtBoxSearchData.Text +"%'";
OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = insertquery;
try
{
OracleDataReader reader = cmd.ExecuteReader();
OracleDataAdapter orada = new OracleDataAdapter(cmd);
DataTable dataTable = new DataTable();
orada.Fill(dataTable);
dataTable.Load(reader);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridViewSearch.DataSource = bSource;
orada.Update(dataTable);
}
catch(ArgumentException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
catch(OracleException ex1)
{
MessageBox.Show("Error: " + ex1.Message);
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
I am positive I do not require all those functions in my Try statement but I have come across many different methods to do this - I just included all of those into my code to experiment. The connection string is correct too as I have succeeded in adding data into the tables through queries in another part of my application.
Doing something like the following should be enough. There should be no need for an OracleDataAdapter or BindingSource. Just can't test it here, as I do not have an Oracle database around.
public void fillDataGrid()
{
try
{
using(OracleConnection connection = new OracleConnection("connectstring"))
using(OracleCommand cmd = new OracleCommand("select * from my super table", connection ))
{
connection .Open();
using(OracleDataReader oracleDataReader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(oracleDataReader );
myDataGrid.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Saving edits to database made in datagridview

How can I adapt my code to any changes that are made remain persistent?
As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.
adb.Update(dt);
However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.
Code
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("#username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("#status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.
You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.
Or generate them with SqlCommandBuilder:
public static DataSet SelectSqlRows(string connectionString,
string queryString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);
//code to modify data in DataSet here
builder.GetUpdateCommand();
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);
return dataSet;
}
}

GridView does not bind with datasource

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();
}

How to filter values in dropdown by entering values in text box

I am trying to bind text box to a dropdown list in C#. I am not able to bind text box and drop down list.
Help me with this code
public void BindDropDownListData()
{
String strConnString = ConfigurationManager.ConnectionStrings["sample11"].ConnectionString;
using (SqlConnection mySqlConnection = new SqlConnection(strConnString))
{
try
{
mySqlConnection.Open();
SqlCommand mySqlCommand = new SqlCommand("dbo.SCM_JOB_DISPLAY", mySqlConnection);
mySqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet);
DropDownList1.DataSource = myDataSet;
DropDownList1.DataTextField = "HTTIS_Issue_Number";
DropDownList1.DataValueField = "HTTIS_Job_Code";
DropDownList1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
mySqlConnection.Close();
}
}
}
try binding
myDataSet.Tables[0]
instead of the whole dataset.

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