Problem with asp.net page results - asp.net

hey guys,
recently while creating a webpage with a gridview, while binding the gridview with sql database, once when i run the site, it shows me the proper results, but when i make any changes and attempt to run the site again, it does not displays the latest changes, instead it displays the results from the previous cache, but when i clears the history, then when i refresh the page, it shows proper results.
Below is my code which i am using to bind my gridview.
SqlConnection con = new SqlConnection(#"[connection string goes here]");
public void FillGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select m.ModuleID, md.FriendlyName from Modules m inner join dbo.ModuleDefinitions md on m.ModuleDefID = md.ModuleDefID", con);
DataTable dt = new DataTable();
adap.Fill(dt);
FunGrid.DataSource = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
FunGrid.DataBind();
}
Below is the source of the gridview as i am using boundfields to bind gridview.
<form id="form1" runat="server">
<div>
<asp:GridView ID="FunGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="10">
<Columns>
<asp:BoundField DataField="ModuleId" HeaderText="Module ID" />
<asp:BoundField DataField="FriendlyName" HeaderText="Module Name" />
</Columns>
</asp:GridView>
</div>
</form>
This is the first time i have got some issues like that, Please if anyone guys have came accross such issues please revert back with the resolutions...
Thanks and Regards
Abbas Electricwala

You can disable caching for the page:
<%# OutputCache Location="None" VaryByParam="None" %>
or add this to your page response:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Related

Displaying Data in GridView using Dataset

I am trying to display a dataset to my ASP.NET application. It seems that when I click the button event, the data is not displaying in the grid.
I have a basic page with the following:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="200" Height="300">
</asp:GridView>
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Then in the code behind, I have the following:
protected void UpdateButton_Click(object sender, EventArgs e)
{
string SQLConfigSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(SQLConfigSettings);
sqlconn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Student", sqlconn);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
UpdatePanel.Update();
}
Am I missing something? Shoudlnt the dataset be diaplayed in the grid?
When I click the button nothing happens.
Thanks :)
You need to add
GridView1.DataBind() right after Gridview1.DataSource.
So it becomes:
...
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
UpdatePanel.Update();
If you need more information about the .DataBind method check MSDN on it
GridView1.DataSource = ds;
Try to mention table inside dataset. Something like ds.Tables[0] or if you know name of table ds.Tables["table_name"]
Put a breakpoint on the first line of code in UpdateButton_Click and run it.
Is that breakpoint reached?
Step through each line of code after that and examine the variable values. Is the DataSet being filled? Can you see the DataTable and its DataRows?
If you reach this event code and have data, then you need to look at the databinding. You need to do GridView.DataBind() immediately after setting the DataSource and before doing the UpdatePanel.Update(). Then you should be good to go.

Dropdown list selected index changed

I did my drop down list that get its values from the database and when running the application, it did not work and the compiler did not see the code.
// aspx
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDlProductFamily" runat="server"
ondatabound="DDlProductFamily_DataBound"
onselectedindexchanged="DDlProductFamily_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DDlProductFamily" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
// cs
protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("SelectThumbByProductFamily", Con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#ProductCategory_Id",
DDlProductFamily.SelectedValue.ToString()));
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
Check if listbox has property AutoPostBack="True".
You need to be loading the DLL data on, for example, Page Load, it is empty so your DDL will never have its SelectedIndex changed.
You need to do something like this psuedo code:
Page_load
{
if(!IsPostBack)
{
BindData();
}
}
BindData()
{
// Do your DataBase/whatever call to fill the DDL
}
And your code for protected void DDlProductFamily_SelectedIndexChanged(object sender, EventArgs e) stays the same.
Your DDL will also need the property AutoPostBack="true"
Do you have AutoEventWireup="true" set in the page directive at the top of your ASPX page? You will need this setting set to true in order for your code to work.
For more information please see Information about the AutoEventWireup attribute:
In Visual Studio .NET or in Visual
Studio 2005, events are bound to
event-handler methods using event
delegates. If you use the Web Forms
Designer to design Web Forms, the
designer automatically generates code
to bind events to their event-handler
methods.

ASP.Net GridView UpdatePanel Paging Gives Error On Second Click

I'm trying to implement a GridView with paging inside a UpdatePanel. Everything works great when I do my first click. The paging kicks in and the next set of data is loaded quickly. However, when I then try to click a link for another page of data, I get the following error:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12030
aspx code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="2"
AllowPaging="true" AllowSorting="true" PageSize="20"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_PageSorting"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ActivityLogID" HeaderText="Activity Log ID" SortExpression="ActivityLogID" />
<asp:BoundField DataField="ActivityDate" HeaderText="Activity Date" SortExpression="ActivityDate" />
<asp:BoundField DataField="ntUserID" HeaderText="NTUserID" SortExpression="ntUserID" />
<asp:BoundField DataField="ActivityStatus" HeaderText="Activity Status" SortExpression="ActivityStatus" />
</Columns>
</asp:GridView>
</contenttemplate>
</asp:UpdatePanel>
code behind
private void bindGridView(string sortExp, string sortDir)
{
SqlCommand mySqlCommand = new SqlCommand(sSQL, mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
mySqlAdapter.Fill(dtDataTable);
DataView myDataView = new DataView();
myDataView = dt.DefaultView;
if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
GridView1.DataSource = myDataView;
GridView1.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
protected void GridView1_PageSorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}
any clues on what is causing the error on the second click?
If anything on your page that is outside UpdatePanel, is changing after the first click, or try to change, on second click is comething diferent, but your calls did get again the fist one value because there are outside UpdatePanel and did not get the update value, just get the first one again -> So product an error on second click.
Probably you have out side the UpdatePanel some data thats need to be rendered correctly.
Keep inside UpdatePanel anything that you change and use with this control.
For example the sSQL, where do you store it ? Its change ? Maybe other value changes on click ?
Probably you have out side the UpdatePanel some data thats need to be rendered correctly. Keep inside UpdatePanel anything that you change and use with this control.

ASP.NET GridView Cell Editing alternative

Is it possible to edit and update a GridView cell without using
<asp:TemplateField> and/or
<%# Eval("Name") %> and/or
<%# Bind("Name") %> and/or
SqlDataSource ?
NB : I want to use only C# code in the behind and SqlConnection, SqlCommand, ExecuteXXX, etc.
NB : Plz provide me code(C# and aspx) or a web-link containing code.
Use onrowediting and onrowupdating in gridview markup...
something like this:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="5" DataKeyNames="Id"
onpageindexchanging="GridView1_PageIndexChanging"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
onsorting="GridView1_Sorting" onrowediting="GridView1_RowEditing">
I am not very sure about winforms, but in websites try this..
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//your code that will edit/update.
}
In general, code with Sqlcommand and Sqlconnection will be something like:
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
Hope this helps.
I still don't figure out why are you fighting against asp.net, but you can do what you want using ObjectDataSource. The ObjectDataSource control uses reflection to call methods of a business object to select, update, insert, and delete data. You set the ObjectDataSource control's TypeName property to specify the name of the class to use as a source object.
Working with ObjectDataSource resume to do things like:
To Declare it:
<asp:objectdatasource
runat="server"
id="ObjectDataSource1"
typename="EmployeeLogic"
selectmethod="GetAllEmployees"
updatemethod="UpdateEmployeeInfo"
dataobjecttypename="NorthwindEmployee" />
To Create Methods into code-behind:
public List<NorthwindEmployee>GetAllEmployees()
{
//your code here
}
public void UpdateEmployeeInfo(NorthwindEmployee emp) {
//your code here
}
to Configure the GridView and to be happy :)
Below I've provided some links that might help you:
http://www.manuelabadia.com/blog/PermaLink,guid,c72852ae-1fdd-4934-a715-f565ceaf21cc.aspx
http://msdn.microsoft.com/en-us/library/57hkzhy5.aspx
http://www.google.com.br/search?hl=en-us&q=objectdatasource+asp.net
A possible solution maybe is to manage the RowDataBound event of the gridview and set the values like
e.Row.Cells(i).Text = value

How to make an ASP.NET TextBox fire it's onTextChanged event fire in an AJAX UpdatePanel?

I am trying to get an textBox to fire it's onTextChanged event every time a keystroke is made rather than only firing only when it loses focus. I thought that adding the AsyncPostBackTrigger would do this but it's still not working. Is what I'm trying to do even possible? The code is below:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Items.aspx.cs" MasterPageFile="~/MMPAdmin.Master" Inherits="MMPAdmin.Items" %>
<asp:Content ID="content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp:ScriptManager ID="sm_Main" runat="server" />
<div style="left:10px;position:relative;width:100%;overflow:hidden">
<asp:UpdatePanel ID="up_SearchText" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tb_Search" EventName="TextChanged" />
</Triggers>
<ContentTemplate>
<div style="position:relative;float:left">
<b style="font-size:xx-large">Items</b>(Add New)
</div>
<div style="right:25px;position:absolute; top:30px">
Search: <asp:TextBox ID="tb_Search" runat="server" Width="200" OnTextChanged="UpdateGrid" AutoPostBack="true" />
</div>
<br />
<div>
<asp:GridView runat="server" AutoGenerateColumns="true" ID="gv_Items" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
You need to call the _postback() function for your textbox control when the onkeyup is raised using javascript.
However, since your textbox is inside your update panel, the textbox will get re-rendered everytime the user hits a key, causing the cursor to loose focus.
This will not be usable unless you get your textbox out of the the updatepanel. That may work out for you, as update panels tend to be a bit slow, you may still have usability issues. - I would suggest using an autocomplete component.
P.S : there is one in the asp.net control toolkit or you could use the jquery autocomplete plugin which I have found to be a bit better.
AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"
Both events are required to trigger text change event.
Dont Need use AJAX controls for checking the availability.. Its is not Compulsory to use it AJAX Controls..
We can use the Following Code..
<iframe>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
RequiredFieldValidator1.ErrorMessage = "";
Label1.Text = "";
string name = TextBox1.Text.ToString();
string constr = "data Source=MURALY-PC\\SQLEXPRESS; database=Online; Integrated Security=SSPI";
SqlConnection con = new SqlConnection(constr);
con.Open();
string query = "select UserName from User_tab where UserName='" + name + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "UserName Already Exists";
}
else
{
Label1.Text = "";
Label1.Text = "UserName Available";
}
con.Close();
}
</iframe>
All the AsyncPostBackTrigger does is make sure only that portion of the page refreshes when the event is fired, it does not change when the event is fired.
I think it's possible to do what you want, but you'd need to write some javascript code to manually fire the event... and I don't even want to think about making that work.

Resources