Binding Gridview from stored procedure - asp.net

I bound my gridview (dgvresult2) reading data from a stored procedure. When I debug my gridview.rows.count it is zero though my DataSet table has 5 rows (ds.Tables[0].Rows.Count).
Kindly assist with this - below is my code:
private void ReturnResult ( )
{
try
{
string connetionString = null;
lblcino.Text = "1234";
connetionString = "Data Source= SLB-84NKBT1\\SQLEXPRESS;Initial Catalog=WireLine Tracking Assets; User=admin; pwd=password123";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand command = new SqlCommand("GetCIno", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#CustomerInvoiceNo", SqlDbType.NChar).Value = lblcino.Text; //((Label)dgvresult.FooterRow.FindControl("lblcino")).Text;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
dgvresult2.DataSource = ds;
dgvresult2.DataBind();
dgvresult2.Visible = true;
}
}
else
{
string message = "ds is Empty";
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
}
connection.Close();
}
catch (Exception)
{
throw;
}
}

Related

how to reduce in multiple try catch

hi i am beginner to develop a project, in my project i used try catch with in try catch so how i write the query professionally...
my code is....
try
{
//connection();
con = new SqlConnection(constr);
con.Open();
txtcusname.Text = "";
txtcusnumber.Text = "";
query = "sample_SP";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GetCusID", txtcusid.Text).ToString();
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GrdCustomerDetails.DataSource = ds;
GrdCustomerDetails.DataBind();
con.Close();
try
{
//connection();
con = new SqlConnection(constr);
con.Open();
ViewState["VSCusID"] = txtcusid.Text;
cmd = new SqlCommand("select contname,mob from CustContacts_TB where cid='" + ViewState["VSCusID"] + " '", con);
dr = cmd.ExecuteReader();
dr.Read();
txtcusname.Text = dr["contname"].ToString();
txtcusnumber.Text=dr["mob"].ToString();
con.Close();
}
catch(Exception ex)
{
}
finally
{
//connection();
con = new SqlConnection(constr);
con.Open();
ViewState["VSCusID"] = txtcusid.Text;
//cmd = new SqlCommand("select compname from CustCreate_TB inner join CustContacts_TB on CustContacts_TB.'" + ViewState["VSCusID"] + "'=CustCreate_TB.'" + ViewState["VSCusID"] + "' ", con);
cmd = new SqlCommand("select compname from CustCreate_TB where cid='" + ViewState["VSCusID"] + " ' ", con);
dr = cmd.ExecuteReader();
dr.Read();
txtcompname.Text = dr["compname"].ToString();
con.Close();
//txtcusname.DataBind();
}
}
catch (Exception ex)
{
}
finally
{
//connection();
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("select compliantID,priorty,status from NewComp1 where customerid='" + ViewState["VSCusID"] + "' and status='open'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grdpending.DataSource = ds;
grdpending.DataBind();
cmd = new SqlCommand("select compliantID,priorty,status from NewComp1 where customerid='" + ViewState["VSCusID"] + "' and status='closed'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
grdClosed.DataSource = ds;
grdClosed.DataBind();
con.Close();
}
it possible to reduce code and it correct format.... thank you for helping and its useful to develop my coding skills
You essentially have:
try
{
[block1]
try
{
[block2]
}
catch(Exception ex)
{
}
finally
{
[block3]
}
}
catch (Exception ex)
{
}
finally
{
[block4]
}
}
They all seem to fetch data and populate controls or variables. You haven't specified what you would do in an exception, so you could simply have them all in a single try block, or put them all in individual blocks. I can't see why they have to be nested.
Finally is usually used for 'clean up' operations, like disposing of open connections but you seem to be using your Finally for a new select & populate operation, which is wrong.
so:
try
{
[block1]
[block2]
[block3]
[block4]
}
or if you needed to know when a specific block had failed but each in try/catch
try
{
[block1]
}
...
try
{
[block4]
}
why are you making all this connection =???
you may do it
try {
using (System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection()) {
if (cnn.State == ConnectionState.Closed)
cnn.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand()) {
//first task
}
using (System.Data.SqlClient.SqlCommand cmd1 = new System.Data.SqlClient.SqlCommand()) {
//second one
}
using (System.Data.SqlClient.SqlCommand cdm2 = new System.Data.SqlClient.SqlCommand()) {
//third task
}
}
} catch (SqlClient.SqlException sqlex) {
//catch exception sql
//to do
} catch (Exception ex) {
//generic exceptio
//to do some stuff
} finally {
//if need to do later
}

data source does not support server-side data paging

i am currently trying to do paging for my gridview but once i allow paging in my gridview it will give me this error : The data source does not support server-side data paging.
this is my code for gridview :
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
conn.Close();
SqlDataReader is forward-only. Server-side Paging needs to be able to traverse the datasource both backward and forward. Use a different datasource, like SqlDataAdapter, which supports bi-directional traversal.
Example (as requested):
string query = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter da = null;
DataSet ds = null;
try {
query = "SELECT * FROM table WHERE field = #value";
conn = new SqlConnection("your connection string");
cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("value", SqlDbType.VarChar, 50).Value = "some value";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
GridView1.DataSource = ds.Tables(0);
GridView1.AllowPaging = true;
GridView1.DataBind();
}
} catch (SqlException ex) {
//handle exception
} catch (Exception ex) {
//handle exception
} finally {
if (da != null) {
da.Dispose();
}
if (cmd != null) {
cmd.Dispose();
}
if (conn != null) {
conn.Dispose();
}
}
SqlDataAdapter is also from the System.Data.SqlClient Namespace.
Have you tried using a SqlDataAdapter to fill a DataSet/DataTable with your SQL results? Then use that DataTable as your data source for the GridView. Basic framework for filling your DataTable:
public DataTable GetDataTable(String connectionString, String query)
{
DataTable dataTable = new DataTable();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
}
}
catch
{
}
return dataTable;
}
And then you can use that DataTable as your GridView DataSource:
String connectionString = "Data Source=<datasource>;Initial Catalog=<catalog>;User Id=<userID>;Password=<password>;";
String query = "SELECT * FROM TABLE_NAME WHERE ID=BLAH";
GridView1.DataSource = GetDataTable(connectionString, query);
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
Hopefully this will help.
You can apply paging to a gridview in two ways
(1) Use an object datasource with your gridview
(2) Use jquery Datatable

Creating DAL for ASP.NET website

I am working on Microsoft Visual Studio DAL in which I am doing the traditional method of fetching/updating the data to show the reviews of the listed items of website by retrieving data from the ItemDetails table of the website database, for creating the ItemDetails.aspx file. I added a DropDownList Control to displaying all items within its categories.
On selection of category from Drop-down list, it shows all items within that category, with a hyperlink attached "Show Details" to it to show details in a grid-view.
i am newbie i have no idea to create DAL for asp.net website. Need easy guidelines to create DAL for asp.net website. Help will be appreciated. What are the other ways to create DAL rather than SQLadapter.
So for example here is a DAL I've used before for calling SPs.
It allows you to execute stored procedures and return dataset, datatables, success responses etc.
Really it depends on how you intend to access the data, will you be writing Stored Procedures or will you have queries in your code. You also have the option of using Entity Framework/LINQ.
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public class _DataInteraction
{
#region "Stored Procedures"
public static DataTable stdReturnDataTableQuery(string procedureName, string db)
{
DataTable myDataTable;
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
cmd.CommandText = procedureName;
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.SelectCommand = cmd;
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((cmd != null))
cmd.Dispose();
}
return myDataTable;
}
// Return a datatable from the database
public static DataTable stdReturnDataTable(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataTable myDataTable = default(DataTable);
string connString = null;
// -----------------------------------------------------------------------
// create instance of connection
// -----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return myDataTable;
}
// Return a dataset from the database
public static DataSet stdReturnDataset(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataSet ds = new DataSet();
string connString = null;
//-----------------------------------------------------------------------
// create instance of connection
//-----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(ds);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return ds;
}
// Return success from a query from the database
public static bool db_NonQuerySuccessResponse(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
string Value = "";
bool success = false;
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
success = true;
}
catch (Exception ex)
{
success = false;
return success;
}
return success;
}
// General non query, no results no success
public static bool db_NonQuery(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
//// Execute scalar on db
//public static string db_Scalar(string strCommandText, ref List<SqlParameter> myParameters, string db)
//{
// SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
// SqlCommand SQLCommand = new SqlCommand();
// string Value = "";
// SQLCommand.CommandText = strCommandText;
// SQLCommand.CommandType = CommandType.StoredProcedure;
// SQLCommand.Parameters.Clear();
// if ((myParameters != null))
// {
// foreach (SqlParameter myParm in myParameters)
// {
// // add the parameter to the command
// SQLCommand.Parameters.Add(myParm);
// }
// }
// SQLCommand.Connection = SQLConnection;
// SQLConnection.Open();
// Value = SQLCommand.ExecuteScalar;
// SQLConnection.Close();
// return Value;
//}
#endregion
}
Below is 1 sample for reference............
public List<T> GetRequests(string strNo)
{
List<T> objlstMapping = null;
Mapping objMapping = null;
try
{
Database objDbInstance = CreateSQLDatabase(DbConnection.MF);
using (DbCommand objDbCommand = objDbInstance.GetStoredProcCommand(Constants.SP_QUESTS))
{
DALBase.AddDbParam(objDbInstance, objDbCommand, "#No", DbType.AnsiString, ParameterDirection.Input, strFolioNo);
objDbCommand.Connection = objDbInstance.CreateConnection();
objDbCommand.Connection.Open();
using (DbDataReader dr = objDbCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
objMapping = new List<T>();
if (dr.HasRows)
{
while (dr.Read())
{
objMapping = new BrokerFolioMapping();
objMapping .Brok_Code = SProposedValue(dr, "Code");
objMapping .Active = SProposedValue(dr, "Status");
objMapping .AccStmt_Active = SProposedValue(dr, "PortfolioStatus");
objlstFolioMapping.Add(objMapping );
}
}
}
}
}
catch (Exception ex)
{
}
return objlstFolioMapping;
}

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources