I have a catalog function whereby user can filter their selection by clicking radiobutton. For example, by selecting the Dining radiobutton, all packages related to dining would appear.
And i using DataList1.Items.Count method to count the number search result. I had implement this method in the page_load, however the value of the number of datalist keep displaying previously loaded datalist.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, CatName from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource1";
if (RadioButtonList1.SelectedIndex == 0)
{
Session["catID"] = 1;
}
else if (RadioButtonList1.SelectedIndex == 1)
{
Session["catID"] = 2;
}
else if (RadioButtonList1.SelectedIndex == 2)
{
Session["catID"] = 3;
}
else if (RadioButtonList1.SelectedIndex == 3)
{
Session["catID"] = 4;
}
else if (RadioButtonList1.SelectedIndex == 4)
{
Session["catID"] = 5;
}
else
{
Session["catID"] = 8;
}
}
I had tried to place the Item.Count in other places of this code, but same problem persist..
Try this,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
}
Related
My problem is the following: I'd like to get some records from a SQL Server table and display them on textboxes in my form.
What I want now is to SELECT these records but filter them with a WHERE condition.
Here's where I connect to the databases I'm using:
private void Form2_Load(object sender, EventArgs e)
{
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.barcodeConnectionString;
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.GetConnection;
MaxRows = ds.Tables[0].Rows.Count;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.barcodeConnectionString;
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL2;
ds2 = objConnect.GetConnection;
MaxRows2 = ds2.Tables[0].Rows.Count;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here's where I grab records:
private void NavigateRecords()
{
dRow = ds.Tables[0].Rows[inc];
if (textBox1.Text == dRow.ItemArray.GetValue(0).ToString())
{
textBox2.Text = dRow.ItemArray.GetValue(1).ToString();
textBox3.Text = dRow.ItemArray.GetValue(9).ToString();
}
}
private void NavigateRecordz()
{
dRow2 = ds2.Tables[0].Rows[inc2];
if (textBox1.Text == dRow2.ItemArray.GetValue(3).ToString())
{
textBox4.Text = dRow2.ItemArray.GetValue(10).ToString();
textBox5.Text = dRow2.ItemArray.GetValue(1).ToString();
}
}
In the tab explore solutions, under Properties --> Settings I got these 2 properties with the following value:
SELECT * FROM DAT_SCOMPART
and like this it's working;
If I try to use
SELECT *
FROM DAT_SCOMPART
WHERE SCO_UDC > 99999
(that's the filter I need) it doesn't return the records anymore.
Any idea on how I could filter the records?
The code is corrected and with this two button click events is working:
private void btnRefresh_Click(object sender, EventArgs e)
{
if (inc < MaxRows -1)
{
inc++;
NavigateRecords();
btnRefresh.PerformClick();
}
else
{
inc = 0;
textBox2.Focus();
}
}
private void btnRefresh2_Click(object sender, EventArgs e)
{
if (inc2 < MaxRows2 - 1)
{
inc2++;
NavigateRecordz();
btnRefresh2.PerformClick();
}
else
{
inc2 = -1;
textBox2.Focus();
}
}
I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}
I work on a search page. I am using 2 repeaters. First to display the results of the search and second to display paging.
The query works just fine if I exclude postback. I can type something in the search box and it appears on the screen. Without the postback, the problem is when I click to go to the second page, I lose the paging repeater. That means I cannot go back to the first page.
So I need this postback to work.
The problem is when the page first loads the text box is empty, therefore I get the following error: "Null or empty full-text predicate."
How to get around it?
Here my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRpt();
}
}
private void BindRpt()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["blabla"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, columnA, columnB, columnC from FREETEXTTABLE (TABLE, columnA , '" + Search.Text + "' ) S, TABLE C WHERE c.columnID = S.[KEY] order by Rank Desc";
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
pgitems.PageSize = 2;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.Count > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
}
else
{
rptPaging.Visible = false;
}
rptResults.DataSource = pgitems;
rptResults.DataBind();
}
public int PageNumber
{
get
{
if(ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set
{ ViewState["PageNumber"] = value; }
}
protected void rptPaging_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindRpt();
}
protected void btnGo_Click(object sender, EventArgs e)
{
BindRpt();
}
Try adding the following as the first line of BindRpt()
if (string.IsNullOrEmpty(Search.Text)) return;
Update following condition:
if (pgitems.Count > 1)
to
if (pgitems.Count > 0)
hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx
In my Web Page, I have 2 List Boxes namely ListBox1,ListBox2.The user select the list of items from ListBox1 and move it to ListBox2.I done up to this, but after i click the 'SAVE' button, it is not save the ListBox2 selected item in the SQL table and It is not throw any error!! how to store it ?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblPage1ID.Text=Server.UrlDecode(Request.QueryString["Parameter"].ToString());
ListBoxWorksPackages();
}
}
protected void ListBoxWorksPackages()
{
ListBox1.Items.Add("General Contractor");
ListBox1.Items.Add("Architecture");
ListBox1.Items.Add("Civil");
ListBox1.Items.Add("Mechanical");
ListBox1.Items.Add("Electrical");
}
protected void btnMoveRight1_Click(object sender, EventArgs e)
{
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListItem li = ListBox1.Items[i];
ListBox1.Items.Remove(li);
}
}
}
protected void btnMoveLeft1_Click(object sender, EventArgs e)
{
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListItem li = ListBox2.Items[i];
ListBox2.Items.Remove(li);
}
}
}
protected void BtnSave1_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
string Packagevalues = string.Empty;
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected == true)
{
Packagevalues += "," + item.Text;
}
}
string query = "INSERT INTO Contractor_Info2 (Vendor_ID,WorksPackage) VALUES"
+ "(#Vendor_ID,#WorksPackage )";
try
{
SqlCommand cmd = new SqlCommand(query, SqlCon);
cmd.CommandType = CommandType.Text;
SqlCon.Open();
cmd.Parameters.AddWithValue("#Vendor_ID", lblPage1ID.Text);
cmd.Parameters.AddWithValue("#WorksPackage", Packagevalues);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
SqlCon.Close();
}
}
you need to call cmd.ExecuteNonQuery() after you've added the parameters to your sql procedure. this is what will actually run your sql statement.
try
{
SqlCommand cmd = new SqlCommand(query, SqlCon);
cmd.CommandType = CommandType.Text;
SqlCon.Open();
cmd.Parameters.AddWithValue("#Vendor_ID", lblPage1ID.Text);
cmd.Parameters.AddWithValue("#WorksPackage", Packagevalues);
// add this
cmd.ExecuteNonQuery();
}