Click here to Skip to main content
15,921,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends, here is my code I just want to know where and when Connection Open/Close should use?
Please for better understanding edit my code and post with your answers.

NOTE: I am not getting an error.
Thank you very much all.

What I have tried:

public partial class Categories : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
PagedDataSource pds = new PagedDataSource();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

try
{
if (!IsPostBack)
{
showData();
}

}
catch (Exception ex)
{
Response.Write(ex.ToString());
}

}

void showData()
{
con.Open();
string catsearch = Convert.ToString(Session["category"]);
string sql = "SELECT * FROM Table_One WHERE Category LIKE @category OR GenreOne LIKE @genre1 OR GenreTwo LIKE @genre2 OR GenreThree LIKE @genre3 OR Audio LIKE @audio OR Language LIKE @language";
SqlCommand cmd = new SqlCommand(sql, con);
//Add the parameters needed for the SQL query
cmd.Parameters.AddWithValue("@category", "%" + catsearch + "%");
cmd.Parameters.AddWithValue("@genre1", "%" + catsearch + "%");
cmd.Parameters.AddWithValue("@genre2", "%" + catsearch + "%");
cmd.Parameters.AddWithValue("@genre3", "%" + catsearch + "%");
cmd.Parameters.AddWithValue("@audio", "%" + catsearch + "%");
cmd.Parameters.AddWithValue("@language", "%" + catsearch + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dt = new DataSet();
da.Fill(dt);

pds.DataSource = dt.Tables[0].DefaultView;
pds.AllowPaging = true;
//pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
pds.PageSize = 20;
pds.CurrentPageIndex = CurrentPage;
Linknext.Enabled = !pds.IsLastPage;
Linkback.Enabled = !pds.IsFirstPage;

DataList2.DataSource = pds;
DataList2.DataBind();
lbl_heading_top.Text = Convert.ToString(catsearch) + " " + "MOVIES LIST";
doPaging();
con.Close();
}
public int CurrentPage
{

get
{
if (this.ViewState["CurrentPage"] == null)
return 0;
else
return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
}

set
{
this.ViewState["CurrentPage"] = value;
}

}
private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");
for (int i = 0; i < pds.PageCount; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}

dlPaging.DataSource = dt;
dlPaging.DataBind();
}

protected void specs_ItemCommand(object source, DataListCommandEventArgs e)
{
string i = Convert.ToString(e.CommandArgument);
Session["id"] = i;
Response.Redirect("Selected_Item.aspx");
}

protected void dlPaging_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
showData();
}
}

protected void Linknext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
showData();
}
protected void Linkback_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
showData();
}

protected void dlPaging_ItemDataBound1(object sender, RepeaterItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;
}
}
}
Posted
Updated 14-Aug-17 8:27am
v3

1 solution

The best way is like this for a DataReader:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT description FROM myTable WHERE Id = @ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", userId);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["Id"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", id, desc);
                }
            }
        }
    }
And this for a DataAdapter:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myDataGridView.DataSource = dt;
        }
    }
The using blocks ensure that the objects are closed and disposed automatically when you are finished with them.
 
Share this answer
 
Comments
navi G 14-Aug-17 14:22pm    
Thanx OriginalGriff You always help me.
OriginalGriff 14-Aug-17 14:26pm    
You're welcome!
Richard Deeming 15-Aug-17 14:55pm    
No need to call Open if you're using a data adapter - it takes care of that for you. :)
OriginalGriff 15-Aug-17 15:18pm    
True ... Just habit, I guess.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900