issues displaying latest news from database onto my website - asp.net

I am having problems in setting a up a latest news panel on my website.
Currently
public System.Data.SqlClient.SqlConnection Admin_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = News();
if (dt.Rows.Count > 0) // Check if the DataTable returns any data from database
{
lbltest.Text = dt.Rows[0]["NewsTitle"].ToString();
lblDate.Text = dt.Rows[0]["NewsDate"].ToString();
lbldescription.Text = dt.Rows[0]["NewsDescription"].ToString();
}
}
protected DataTable News()
{
DataTable dt = new DataTable();
SqlDataAdapter data = new SqlDataAdapter("SELECT NewsTitle, NewsDescription, NewsDate FROM News WHERE [NewsDate] < getdate()", Admin_conn);
data.Fill(dt);
return dt;
}
But the above code just display news of single row.. I want to display all the news on my website. Which control should I use to display all the records from the database in a proper order like news title, news description then the next news title and description.....
Is there any way to use ajax accordion so that all the news title will be displayed and when I click on the specific news title, the description of that news will be displayed.
Any suggestions or tutorial will be highly appreciated..

I believe you are looking for the ListView Control.
It will allow you to bind to the entire set of rows being returned from the database and provide a template for each item.
You can also take a few minutes to watch this video tutorial from Microsoft:
The ListView Control: The Official Microsoft ASP.NET Site

Related

Filtered data refreshes to unfiltered data when clicking next page of web forms GridView

I have a web forms project that has one filter. When the user filters the data and clicks on the next page, the filter seems to get taken off and the default data is displayed. How can I fix this? Is it the OnPageIndexChanging attribute method that needs updating? I've shown the code behind below for the ONPageIndexChanging method and the method used to bind the data (had to cut some out to get rid of the "too much code" error but if I'm missing anything that would be helpful, please let me know.)
protected void dashboard_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dashboard.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
void BindDataToGridView(SqlCommand cmdSQL = null)
{
// default sql
if (cmdSQL is null)
{
cmdSQL = new
SqlCommand("SELECT TabID, TabName, Title, CreatedOnDate, TabPath From [tableName].[dbo].[Tabs] Order By TabName");
}
var connectionFromConfig = WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
using (cmdSQL)
{
cmdSQL.Connection = new SqlConnection(connectionFromConfig);
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
dashboard.DataSource = rst;
dashboard.DataBind();
}
}
}
In place of your BindDataToGridView() for the paging event?
Call the SAME routine you have for the button click to filter the dates.
(you could even pull out the code for the button click into a separate routine. That routine filters by date, so have both your button click to filter, and the page index change event call that same routine.
So, for paging, you have to call the routine with the filter. This kind of suggests that you want one routine to load the grid, and it has to figure out if you have a filter or not. So, you might check for start/end date being blank. this would allow both page load event, the filter button, and the data page change event ALL to call ONE common routine.
So, a few things:
If you going to bind a grid/list view? and page? And filter?
(3 issues)?
Then make ONE common routine for all to call.
Say like this:
void BindDataToGridView()
{
SqlCommand cmdSQL = new SqlCommand("");
cmdSQL.CommandText = "SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName Order By TabName";
if (startDate.Text != "")
{
// filter
cmdSQL.CommandText =
"SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName " +
"WERE CreatedOnDate >= #Start AND <= #End ORDER By TabName";
cmdSQL.Parameters.Add("#Start", SqlDbType.Date).Value = startDate.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Date).Value = endDate.Text;
}
using (cmdSQL)
{
cmdSQL.Connection = new SqlConnection(conString);
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
dashboard.DataSource = rst;
dashboard.DataBind();
}
}
So now we are NOT passing the filter. You could I suppose also put the sql or the status of the filter into view state, and have the filter routine check this, but you better off to do the above.
In fact, I often suggest that we filter the reocrdset against its built in "view", as that can save database hits, but it don't matter.
So, when introducing filters? AND paging? You have to keep the above in mind.
So, now we have one routine for page load, the button click and the pager changing index code.

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

How can I pass parameter to Reportviewer?

I am trying to create report for TOP (according to user provide say 10,100,200..) products. I am 90% success with it. Now, I am finding difficulties to show this numbers to Report header. So, my report header is saying Top Products, now I want to make this dynamic, saying Top 100 Products, Top 200 Products.
I AM USING VS 2008.
For this, I created parameter in ReportViewer. I tried this code in Page_Load event ;
protected void Page_Load(object sender, EventArgs e)
{
ReportDataSource rds = new ReportDataSource("SP_GetProductsbySales_DataSet");
//ReportViewer1.ServerReport.ReportPath = "Report1.rdlc";
ReportViewer1.LocalReport.ReportPath = "Report1.rdlc";
ReportParameter[] param = new ReportParameter[1];
param[0] = new ReportParameter("top", "100");
ReportViewer1.ServerReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();
}
but getting error saying : The source of the report definition has not been specified.
How can I accomplish this one? I tried to google as well as watched some videos, but still I am not getting any idea.
Thanks.
Please set data source
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
You can set an expression in your report to show the value.
The expression would be as follows:
="Top " & Parameters!top.Value & " Products"

Dynamically update dropdownlist

I have this dropdownlist populated and everything. The only problem is that whenever I add a new item in the database through my website, the dropdownlist doesn't update for some reason.
private CurrentUser _cu = new CurrentUser();//just to check if use is an admin or not.
protected void Page_Load(object sender, EventArgs e)
{
_cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!_cu.CanReport) { Response.Redirect("~/default.aspx"); }
CurrentUser cu = (CurrentUser)Session[Common.SessVariables.CurUser];
if (!IsPostBack)
{
foreach (PrefixAdd loc in cu.Prefix)//Prefix is a Property
{
ListItem x = new ListItem(loc.Prefix);
PrefixID.Items.Add(x);
}
}
}
#Wayne I'm using a store procedure to just insert a Prefix like Pre,yes,sey, etc. Then the list is populated with prefixes.
StringBuilder sbSQL = new StringBuilder(255);
sbSQL.Append(string.Format("exec insPrefix #Prefix=N'{0}';", PrefixBox.Text.Trim()));
string msg = string.Empty;
msg = (_oDAW.ExecuteNonQuery(sbSQL.ToString())) ? string.Format(Common.GetAppSetting(Common.ConfigKeys.User_Submit_Success),
PrefixBox.Text.Trim()) : Common.GetAppSetting(Common.ConfigKeys.SubmitFail); //this is a somewhat custom method for CS and databinding.
# Yuriy Rozhovetskiy Yea I add new items to this page with the dropdownlist.
Whenever you add an item to your database, you have to rebind your drop down list.
yourDropDown.DataSource = //...
yourDropDown.DataBind();
That is, DropDownLists (and other controls) have no way of knowing that their data has changed behind the scenes, they can't automatically detect it. You have to tell the controls to rebind their data manually.
Good job on the Page_Load(...){ if !(IsPostback) part.
Since you add new prefix on this page with some postback item you need to add this new item to PrefixID dropdown's Items collection and update the CurrentUser instance in Session right after you have add new prefix to database.

ASP.net DataTable doesn't store new rows

In my simple starter asp page I create a DataTable and populate it with two rows. The web site allows users to add new rows. My problem is the DataTable doesn't save the information. I've stepped through the code and the row gets added but the next time a row is added it's not there, only the original two and the newest one to get entered.
I have gotten around this, in an inelegant way, but am really curious why the new rows are being saved.
My code:
protected void Page_Load(object sender, EventArgs e)
{
_Default.NameList = new DataTable();
DataColumn col = new DataColumn("FirstName", typeof(string));
_Default.NameList.Columns.Add(col);
col = new DataColumn("LastName", typeof(string));
_Default.NameList.Columns.Add(col);
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
_Default.NameList.Rows.Add(row);
row = _Default.NameList.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Doe";
_Default.NameList.Rows.Add(row);
}
protected void AddButton_Click(object sender, EventArgs e)
{
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = this.TextBox1.Text;
row["LastName"] = this.TextBox2.Text;
_Default.NameList.Rows.Add(row);
_Default.NameList.AcceptChanges(); // I've tried with and without this.
}
I've tried saving them to GridView control but that seems like quite a bit of work.
I'm new to ASP.Net but have done windows programming in C# for the last two years.
You're creating a new DataTable object each time the page loads.
You need to persist the DataTable object to session state or a static variable, or save the data to a database.
Remember that handling events like your button click requires a full postback. You don't run just the click code, you run your entire page lifecycle on a new instance of your page class. The new instance of your page class means a new instance of the datatable as well.
The issue here is that your DataTable is being created every time your page loads and it goes out of scope when your page has finished loading and been displayed to the user. To get your desired effect, you will need to store the DataTable in either Session, ViewState, cache, use a control like GridView that will automatically store the underlying data in its state, or something else.
Since you're new to ASP.NET, check out your options for state management.

Resources