ASP.NET Repeater and CollectionPager [duplicate] - c#

I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}

the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx

try this EnableViewState="false"

You have to bind the CollectionPager again on your search.

Related

fetch data from two different tables on same textbox changed event

I want to fetch some data from two different tables PRO and OPN_STK , in some controls like textboxs and datagridview . when i am selecting data from one table i.e. PRO ,the code is working perfect but when i applied same code just next to it , in same event for fetching data from another table i.e. OPN_STK it throws exception "object refrence not set to an instance of object" . I tried to know about the problem but now I'm blank , this is what I did ,
private void comboProname_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
//if (get == false) //in case when i need to apply condition which I dont prefer
{
string _sql = "select DISTINCT P_batchno,P_sh from PRO where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
//else if (get == true) // opnstk
{
string _sql = "select DISTINCT P_batchno,P_sh from OPN_STK where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
getdata();
}
private void comboBthNo_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
// if (get == false)
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from PRO where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
// else if (get == true) ///// opn stk ///////
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from OPN_STK where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows) // I get exception here only on dt
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
getdata();
}
i would appriciate any help ,thanks in advance .
Put a breakpoint in your code, debug and check that OPN_STK is not null. If it is null that would be your problem.

ASP.NET Manual ListBox Filters for GridView

I have multiple ListBoxes as Categories, Departments, Faculties etc. And I have a GridView populated from database (MSSQL) in code-behind. I will use ListBoxes as filters.
For example, when i choose a category from CategoriesListBox, the GridView will show only the entries in this category. And when I also choose a Department, the GridView will show only the entries in selected category and department.
I suppose that I will do it by use of selectedIndexChanged event of ListBoxes. My aspx code is:
public partial class Default : System.Web.UI.Page
{
private string constr = MY_CONNECTION_STRING;
protected void Page_Load(object sender, EventArgs e)
{
FillGridView();
}
protected void FillGridView()
{
string Query = "SELECT * FROM Entry WHERE Category = '" + SelectedCategory +"' AND Department = '" + SelectedDepartment +"'";
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(Query, conn);
try
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("Hata: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedCategory value and re-fill GridView
}
protected void DepartmentsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedDepartment value and re-fill GridView
}
}
Thanks for help.
you can do it by select from your table where CategoryName =#parameter in your connection string
#parameter is your listbox selectedItem or selected value.
Using your own code, why not pass the category and department to the FillGridView? And if one of those are null it would mean no filter at all. So, something like this:
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
FillGridView(lbCategory.SelectedItem.ToString(), lbDepartment.SelectedItem.ToString());
}
The same would be applied on the DepartmentsListBox_SelectedIndexChanged event.
Then change the FillGridView function to:
protected void FillGridView(string SelectedCategory, string SelectedDepartment)
Also, if I may I'd suggest to gather all the table contents at once, save data to an in-memory copy and filter them from said copy, this would enable a much more fast and better user experience imo.
Edit:
if (selectedCategory.Trim() == "")
selectedCategory = "IS NOT NULL";
else
selectedCategory = " = \'" + selectedCategory.Trim() + "\'";
if (selectedDepartment.Trim() == "")
selectedDepartment = "IS NOT NULL";
else
selectedDepartment = " = \'" + selectedDepartment.Trim() + "\'";
string Query = "SELECT * FROM Entry WHERE Category " + SelectedCategory + " AND Department " + SelectedDepartment;
Add it to the beginning of the FillGridView function (this is just a quick & easy hack, not the best solution).

Dataset showing unexpected Data

I have 2 ListBoxes and five textBox. In ListBox_prod i want to retrieve all product (from PRODUCT table) and in Listbox_item i want to retrieve all Items corresponding to the selected Product (from PRODITEM table) on form load event. All the products have more than 1 items associated with them. Problem is with the Listbox_item as it is showing only 1 item. But I want all items to be displayed in Listbox_item when a particulat product is selected. getData() in class DBCommands actually causes the problem. Here's my code:
public partial class form_prodItems : Form
{
private DBCommands dBCommand;
public form_prodItems()
{
InitializeComponent();
listBx_prod.SelectedIndexChanged += new EventHandler(listBx_prod_selValChange);
listBx_item.SelectedIndexChanged += new EventHandler(listBx_item_selValChange);
}
private void form_prodItems_Load(object sender, EventArgs e)
{
// ...
refresh_listBx_prod("PRODUCT", this.listBx_prod, null, null);
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void listBx_item_selValChange(object sender, EventArgs e) // causing problem
{
if (listBx_item.SelectedValue != null)
showPrice("PRODITEM", listBx_item.ValueMember, listBx_item.SelectedValue.ToString());
}
private void listBx_prod_selValChange(object sender, EventArgs e)
{
if(listBx_prod.SelectedValue != null)
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void showPrice(string tblName,string where_column ,string where_val)
{
DataSet ds;
ds = dBCommand.getData("select * from " + tblName + " WHERE " + where_column + " = '" + where_val + "'");
DataRow col_val = ds.Tables[0].Rows[0];
txtBox_12oz.Text = col_val.ItemArray[3].ToString();
txtBox_16oz.Text = col_val.ItemArray[4].ToString();
txtBox_20oz.Text = col_val.ItemArray[5].ToString();
txtBox_1lbs.Text = col_val.ItemArray[6].ToString();
txtBox_2lbs.Text = col_val.ItemArray[7].ToString();
//ds.Clear();
}
private void refresh_listBx_prod(string tblName, ListBox listBox, string where_column, string where_val)
{
DataSet ds = new DataSet();
dBCommand = new DBCommands();
if (where_column == null)
{
ds = dBCommand.getData("SELECT * FROM " + tblName);
}
else
{
ds = dBCommand.getData("SELECT * FROM " + tblName + " WHERE " + where_column + " = " + where_val);
}
listBox.DataSource = ds.Tables[0];
// ds.Clear();
}
}
public class DBCommands
{
private SqlConnection conn;
private SqlDataAdapter dataAdapter;
private DataSet container;
public DataSet getData(string selectCmd)
{
container.Clear(); // I guess something needs to be fixed here some where..
conn = getConnection();
dataAdapter.SelectCommand = new SqlCommand(selectCmd, conn);
dataAdapter.Fill(container);
conn.Close();
return container;
}
private SqlConnection getConnection()
{
SqlConnection retConn = new SqlConnection("Data Source=" + Environment.MachineName + "; Initial Catalog=RESTAURANT; Integrated Security = TRUE");
retConn.Open();
return retConn;
}
}
Actually dataset flushes all data it had got from (SELECT * FROM PRODITEM where PRODUCT_id = '1') and shows data from the last executed query i-e (select * from proditem where item_id = 1)
Any suggestions..
my suggestion is trying to run the command via SqlCommand.
that way you will have better knowledge on what you get back.
use this example:
SqlCommand command = new SqlCommand(selectCmd, conn);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
and modify it so you'll return a table as you need.
the reason i offer you this is that it's easy to use and you get immediate debug information that help you understand sql mistakes

Displaying a progressbar while executing an SQL Query

I want to inform the user while data is being read from an SQL database
and I decided to create a form with a progressbar but it doesn't work - maybe because a thread is needed. I want to create the form programmatically
ProgressBar pb = new ProgressBar();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size(200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add(pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show();
//do data processes here (all queries and executes)
progressForm.close();
How do I modify the code above to achieve my stated goals?
edit: Btw, I want to use this progressbar form in every data functions in my project. For example: fillGrid, runQuery..
#Will thank you very much for your answers. I meant how can I use a function of class for example my gridFill function is in that connection class:
class ConnectionClass
{
public static SqlConnection connection = new SqlConnection();
public string sorgu;
public static string server;
public static string userId;
public static string catalog;
public static string password;
public static string accessMethod;
public DataSet ds = new DataSet();
Form progressForm = new Form();
public bool Open()
{
try
{
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = "Data Source = " + server + ";" +
"Initial Catalog=" + catalog + ";" +
"User ID=" + userId + ";" +
"Password=" + password + ";" +
"Connect Timeout=0";
connection.Open();
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show("System message:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public DataTable Dt(string query)
{
DataTable dt = new DataTable();
if (Open())
{
SqlDataAdapter da = new SqlDataAdapter(query, connection);
try
{
//progressForm.Showdialog() is this possible???
da.Fill(dt);
//progressForm.close(); ??
}
catch (Exception ex)
{
MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
public bool Run(string query, string hataMsj)
{
Form activeForm = Form.ActiveForm;
query = " SET DATEFORMAT DMY " + query;
SqlCommand sc = new SqlCommand(query, connection);
try
{
Open();
sc.ExecuteNonQuery();
return true;
}
catch (Exception )
{
return false;
}
}
public void fillComboBox(string sorgu, ComboBox cb, string text, string value)
{
DataTable dt = Dt(sorgu);
cb.DisplayMember = text;
cb.ValueMember = value;
cb.DataSource = dt;
if (cb.Items.Count > 0)
{
cb.SelectedIndex = 0;
}
}
public int fillGridView(string sorgu, DataGridView dgv)
{
DataTable dtGrvw = Dt(sorgu);
dgv.DataSource = dtGrvw;
return 1;
}
}
and example queries from another form(class)
ConnectionClass cc = new ConnectionClass();
query= " INSERT INTO tblPersonel (" +
" [sqlUserName] " +
",[personelNo] " +
",[ad] " +
",[soyad] " +
",[departmanId] " +
",[emailadres] " +
",[tcKimlikNo],[kangurubu],[dokumaciNo])VALUES" +
"('" + tbSqlUserName.Text +
"','" + tbPersonelNo.Text +
"','" + tbAd.Text +
"','" + tbSoyad.Text +
"','" + cbDepartman.SelectedValue.ToString() +
"','" + tbMail.Text +
"','" + tbKimlikno.Text +
"','" + tbKangrubu.Text +
"','" + tbDokumaciNo.Text + "' ) ";
if (cc.Run(query, "Unexpected error on insert new person"))
{
fillGrid();
this.Close();
}
public void fillGrid()
{
query= " select * from View_Personel order by personelNo desc";
cc.fillGridView(query, gridviewPersonel);
}
and I cant imagine how can I use it in bw_DoWork event. because my function has parameters.(query, gridview) when I call it from another class I can use it with parameters...
p.s. : this Method is pretty good for me but it didnt worked. I didnt understand the problem
Use the BackgroundWorker class to fill your DataGrid.
Form progressForm;
public void func() {
BackgroundWorker bw = new BackgroundWorker ();
bw.DoWork += new DoWorkEventHandler (bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler (bw_RunWorkerCompleted);
progressForm = new Form ();
ProgressBar pb = new ProgressBar ();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size (200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add (pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show ();
string queryString = "SELECT ...."; // fill query string here
var params = new KeyValuePair<GridControl, string>(sorgu, queryString);
bw.RunWorkerAsync (params);
}
void bw_DoWork (object sender, DoWorkEventArgs e) {
KeyValuePair<GridControl, string> params = e.Argument as KeyValuePair<GridControl, string>;
ConnectionClass cc = new Connection Class();
cc.fillGrid(params.Value, params.Key);
}
void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {
progressForm.Close (); //
}
It is possible to send a parameter to the BackgroundWorker. If you need more than one parameter, you can send a Tuple which contains any objects you need.
EDIT: If you're on 3.5, you can use a KeyValuePair instead. Code is updated for that.
Just as Ash Burlaczenko recommended, you'll have to use a BackgroundWorker for that purpose.
Since, however, you'd like to tie it in with a ProgressBar, I'd recommend looking at this article on CodeProject: ProgressWorker.
It's fairly easy to use and it updates the progress bar for you automatically. All you'll have to do is remember to call the ProgressWorker.ReportProgress method from time to time in order to update the associated progress bar.

ADO.NET connection error "System.Data.OleDb.OleDbException"

I am getting this error while trying to connect my web site.
Unspecified error Description: An
unhandled exception occurred during
the execution of the current web
request. Please review the stack trace
for more information about the error
and where it originated in the code.
Exception Details:
System.Data.OleDb.OleDbException:
Unspecified error.
Maybe I am doing something wrong while opening and closing connections. I always get this error if 5-10 user enter same time to site. When a user enter site I am updating or inserting new records for statistics.
I am using db class for connect:
public OleDbConnection baglan()
{
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("~/App_Data/manisaweb.mdb"));
baglanti.Open();
return (baglanti);
}
//********************************************************************
//Sql Sorgu Çalıştırma
public int cmd(string sqlcumle)
{
OleDbConnection baglan = this.baglan();
OleDbCommand sorgu = new OleDbCommand(sqlcumle, baglan);
int sonuc = 0;
try
{
sonuc = sorgu.ExecuteNonQuery();
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sqlcumle + ")");
}
finally
{
sorgu.Connection.Close();
}
return (sonuc);
}
//********************************************************************
//Kayıt Sayısı Bulma
public string GetDataCell(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0)
return null;
return table.Rows[0][0].ToString();
}
//Kayıt Çekme
public DataRow GetDataRow(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0) return null;
return table.Rows[0];
}
//DataTable ye veri çekme
public DataTable GetDataTable(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
adapter.Dispose();
baglan.Close();
}
return dt;
}
//Datasete veri çekme
public DataSet GetDataSet(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
ds.Dispose();
adapter.Dispose();
baglan.Close();
}
return ds;
}
And for STATISTICS in main.master.cs every page_load event
public void Istatistik()
{
string IpAdres = Request.ServerVariables["REMOTE_ADDR"].ToString();//Ip Adresini alıyoruz.
string Tarih = DateTime.Now.ToShortDateString();
lblOnlineZiyaretci.Text = Application["OnlineUsers"].ToString();//Online ziyaretçi
//Ogüne Ait Hit Bilgi Güncelleme
DataRow drHit = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
if (drHit == null)
{
//Bugüne ait kayıt yoksa bugunün ilk siftahını yap
cmd("Insert into SayacHit(Tarih,Tekil,Cogul) values('" + Tarih + "',1,1)");
}
else
{
string SayfaAdi = Page.ToString().Replace("_aspx", ".aspx").Remove(0, 4); //Sayfa adını alıyoruz.
if (SayfaAdi == "default.aspx")//Güncelleme işlemini sadece anasayfadaysa yapıyoruz
{
//Bugüne ait kayıt varsa Çoğulu 1 artırıyoruz.
cmd("Update SayacHit set Cogul=Cogul+1 Where Tarih='" + Tarih + "'");
}
//Tekil artımı için önce Ip kontrolü yapıyoruz.
DataRow drIpKontrol = GetDataRow("select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIpKontrol == null)
{ //Eğer ip yoksa tekilide artırabiliriz. Ip kayıtlı ise artırma işlemi yapmıyoruz.
cmd("Update SayacHit set Tekil=Tekil+1 Where Tarih='" + Tarih + "'");
}
}
//Giren Kişinin IP sini Kaydetme
DataRow drIp = GetDataRow("Select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIp == null)
{
cmd("Insert into SayacIp(Ip,Tarih) values('" + IpAdres + "','" + Tarih + "')");
}
//Ekrana Bilgileri Yazdırabiliriz
DataRow drSonuc = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
lblBugunTop.Text = drSonuc["Cogul"].ToString();
//lblBugunTekil.Text = drSonuc["Tekil"].ToString();
//Dün Bilgilerini Çekme
//DataRow drDun = GetDataRow("Select * from SayacHit Where Tarih='" + DateTime.Now.AddDays(-1).ToShortDateString() + "'");
DataRow drGenel = GetDataRow("Select SUM(Tekil) as Toplam from SayacHit");
//if (drDun != null)
//{
// lblDunTop.Text = drDun["Tekil"].ToString();
//}
//else
//{
// lblDunTop.Text = "0";
//}
lblGenelTop.Text = drGenel["Toplam"].ToString();
lblIPAdresi.Text = IpAdres;
}
And then there is 2 section in Default.aspx; it loads at the page load event for news and articles.
db veri = new db();
rptNews.DataSource = veri.GetDataTable("select top 5 KullaniciAdiSoyadi,Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik a inner join Kullanici d on a.KullaniciID=d.KullaniciID where KategoriID = 1 and Durum = 1 Order by IcerikID Desc ");
rptNews.DataBind();
rptArticle.DataSource = veri.GetDataTable("select top 5 Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik where KategoriID = 2 and Durum = 1 Order by IcerikID Desc ");
rptArticle.DataBind();
So there is so many UPDATE, INSERT and SELECT queries in every page load event. If this is my problem, is there another way of doing this?
It would help if you showed a bit more of the code. With this much information it could be anything. I'll take 2 guesses:
1) You have a limit of 5 connections, either on your Db or in ConnectionPooling
2) You forgot to close (Dispose) one or more Database objects
I would second Henk's #2 suggestion: failure to properly close database connections. If you are using DataSets or DataReaders, sending inline SQL or calling stored procedures, you must close the connections in code when you are through with them. If you don't close the connection, the number of available connections is gradually maxed out, and no new database requests can be made. It is only after enough users' sessions time out and the connections are released that other users can obtain a connection.
You have the exact symptom of unclosed connections: everything works fine for the first few users. But gradually, as more users log in, or as the original users move about the web app, opening ever more database connections, that everything locks up.
One way to diagnose this would be to use a database profiler tool (Profiler for SQL Server) to examine the database connections as they are opened and closed.

Categories