Manual Databind in Gridview Paging - asp.net

Server Error in '/' Application.
--------------------------------------------------------------------------------
The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.
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.Web.HttpException: The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.]
System.Web.UI.WebControls.GridView.OnPageIndexChanging(GridViewPageEventArgs e) +1325594
System.Web.UI.WebControls.GridView.HandlePage(Int32 newPage) +86
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +464
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +207
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
when using this function and enable paging = true
private void BindGrid(string sqlQuery, ref GridView gv)
{
SqlConnection sqlConnection = null;
try
{
sqlConnection = new SqlConnection(strConnect);
SqlCommand scom = new SqlCommand(sqlQuery, sqlConnection);
scom.CommandTimeout = 100;
sqlConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(scom);
DataTable dt = new DataTable();
adapter.Fill(dt);
gv.DataSource = dt;
gv.DataBind();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
if (sqlConnection != null) sqlConnection.Close();
}
}

Add a handler for PageIndexChanging event.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
.....
.....
GridView1.DataSource=dt;
GridView1.DataBind();
}

Try, this code:
int newPagenumber = e.NewPageIndex;
GridView1.PageIndex = newPagenumber;
GridView1.DataSource = call the method that will fill ur dataset.
GridView1.DataBind();

Related

{"Object reference not set to an instance of an object."}

Creating a ASP.NET form with C#, i am facing this error i don't know what is the error with it. Its all doing fine but when i push the save Button it gives me this error:
NulllRefrenceException was unhandled by user code
{"Object reference not set to an instance of an object."}
Object reference not set to an instance of an object.
Code:
protected void Button8_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlAddSave"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from DisplayPP";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " DisplayPP ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["DisplayPP"].NewRow();
drow["website"] = web.Text;
drow["country"] = DropDownList1.SelectedItem.Text;
drow["contact"] = TextBox144.Text;
drow["cat"] = TextBox145.Text;
drow["traff"] = TextBox146.Text;
more text boxes as above
ds.Tables["DisplayPP "].Rows.Add(drow);
da.Update(ds, " DisplayPP ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
}
please help.
Connection String:
<add name="sqlAddSave" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\PPTableDisplay.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Exception
Exception Details: System.NullReferenceException was unhandled by user
code HResult=-2147467261 Message=Object reference not set to an
instance of an object. Source=TestCRole StackTrace: at
TestCRole._Default.Button8_Click(Object sender, EventArgs e) in
c:\Users\xxxxx\Documents\Visual Studio
2012\Projects\WindowsAzure2\TestCRole\Default.aspx.cs:line 60 at
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
ds.Tables["DisplayPP "].Rows.Add(drow);
should be this
ds.Tables["DisplayPP"].Rows.Add(drow);

Exception when reading file image on server - ASP.NET

i hope anyone help me in this problem ..
i have simple aspx code to get image file from directory and make some proccesses on it as drawing somthing on it after that i save it on the same directory.
really the code has worked well on local machine, but on server side the code fails and the exception appears. ( ArgumentException: Parameter is not valid )
please look at the code :
DirectoryInfo[] dir = new DirectoryInfo[2];
dir[0] = new DirectoryInfo(Server.MapPath("Image/DB/Large/"));
dir[1] = new DirectoryInfo(Server.MapPath("Image/DB/Thumb/"));
System.Drawing.Image signature = System.Drawing.Image.FromFile(Server.MapPath("Image/Design/signature.png"));
for (int i = 0; i < dir.Length; i++)
{
FileInfo[] fs = dir[i].GetFiles("*.jpg");
foreach (FileInfo s in fs)
{
FileStream strm = s.OpenRead();
String name = s.Name;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(signature, new Point(0, 0));
strm.Close();
if (i == 0)
{
String v = Server.MapPath("Image/DB/Large/" + name);
img.Save(v);
}
else if (i == 1)
{
String v = Server.MapPath("Image/DB/Slide/" + name);
img.Save(v);
}
g.Dispose();
}
}
Exception Details :
Parameter is not valid.
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.ArgumentException: Parameter is not valid.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Parameter is not valid.]
System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) +1062843
System.Drawing.Image.FromStream(Stream stream) +8
Developer.Button1_Click(Object sender, EventArgs e) +279
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
You must convert your FileStream to Stream
System.Drawing.Image.FromStream(..);// This method take Stream as argument and nor FileStream
You can try with CopyTo, in order to convert.
Link : http://msdn.microsoft.com/en-us/library/dd782932.aspx
FileStream strm = s.OpenRead();
Stream stream = new Stream();
strm.CopyTo(stream);
System.Drawing.Image.FromStream(stream);
Before .Net 4, you can use this extension method
public static class Ext
{
public static void CopyTo(this FileStream in, Stream out)
{
byte[] temp= new byte[16*1024]; //You can adjust this value
int bytesRead;
while ((bytesRead = in.Read(temp,0, temp.Length)) > 0)
{
out.Write(temp, 0, bytesRead);
}
}
}

ASP.NET Form View IF on Updating

I want to run an if before updating a form view;
if yes then..."message" & cancel update query
if no continue update query.
i've tried this but i'm getting a "obeject instance not set to null instance......" on the first line of the if? and the item updates regardless
Private Sub FormView2_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles FormView2.ItemUpdating
Dim status As TextBox = FormView1.FindControl("ApprovalStatusTextBox")
If status.Text = "approved" Or "denied" Then
e.Cancel = True
lblupdaterequest.Text = "you cannot update this request as it has already been responded to"
Else
HolidayDetailsdatasource.Update()
End If
Anyone aware of a better was of achieving something like this?
exact error:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=WebApplication1
StackTrace:
at WebApplication1.HolidayApprovalDetails.DetailsView1_ItemUpdating(Object sender, DetailsViewUpdateEventArgs e) in line 32
at System.Web.UI.WebControls.DetailsView.OnItemUpdating(DetailsViewUpdateEventArgs e)
at System.Web.UI.WebControls.DetailsView.HandleUpdate(String commandArg, Boolean causesValidation)
at System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I can at least see that you are retrieving the value of the status TextBox from 'FormView1', while your sub ItemUpdating is referring to 'FormView2'.
After changing this, try adding a message box before the if, to make sure you got the right value you wanted:
MsgBox(status.Text)
Hopefully, it helps you solve your problem.
If status IsNot Nothing AndAlso (status.Text = "approved" OrElse status.Text = "denied") Then

Changing Entity connection string error

I am having a problem when changing the model entities connection string,
when a user first logs in the KurtDBEntities conection string is being chosen properly
but when logging in as an admin if (daRoles.IsUserInRole(User, 1)) or any other instance it is giving me this error:
System.InvalidOperationException was unhandled by user code
Message=No modifications to connection are permitted after the metadata has been registered either by opening a connection or constructing the connection with a MetadataWorkspace.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityClient.EntityConnection.ValidateChangesPermitted()
at System.Data.EntityClient.EntityConnection.set_ConnectionString(String value)
at DataLayer.ConnectionClass..ctor(String User) in Documents\Visual Studio 2010\Projects\DataLayer\ConnectionClass.cs:line 32
at BusinessLayer.BLBase..ctor(String user) in Documents\Visual Studio 2010\Projects\BusinessLayer\BLBase.cs:line 54
at BusinessLayer.Roles..ctor(String userLogged) in Visual Studio 2010\Projects\BusinessLayer\Roles.cs:line 12
at PresentationLayer.UserControls.Menu.Page_Load(Object sender, EventArgs e) in C:\Users\Documents\Visual Studio 2010\Projects\PresentationLayer\UserControls\Menu.ascx.cs:line 23
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
and:
public ConnectionClass(string User)
{
this.Entities = new KurtDBEntities();
DataLayer.DARoles daRoles = new DARoles(this.Entities);
if (User == "Login")
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
else
{
//can also use entity connection string builder
if (User != "")
{
if (daRoles.IsUserInRole(User, 1))
{
this.Entities.Connection.ConnectionString = #"Data Source=KURT-PC\SQLEXPRESS;Initial Catalog=KurtDB;User ID=Admin;Password=123456";
}
else if (daRoles.IsUserInRole(User, 2))
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["BasicUser"].ConnectionString.ToString();
}
}
else
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
}
//this.Entities.Connection.ConnectionString = conn;
}
}
Any Help Please?
Please see my answer to your other question:
You'll need to first determine the connection string that you want to use and only after that you'll be able to new up the Entities object:
string connectionString = GetConnectionStringBasedOnUserRole(); // do your magic here
this.Entities = new KurtDBEntities(connectionString);
After this you should be able to use Entities normally, pointing to the correct database/server.

How to clear error in asp.net

i have been designing a web page in asp.net and my project is successful. and i published my web application.However, below error occurs.How can I clear it?
Server Error in '/sarav' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Login.btnLogin_Click(Object sender, EventArgs e) +155
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
How to clear error
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection Cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != null)
{
constr = ConfigurationManager.ConnectionStrings["PhotostudioConnectionString"].ConnectionString;
Cnn.ConnectionString = constr;
try
{
if (Cnn.State != ConnectionState.Open)
Cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = Cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UspGetDataUsrmast";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#usrname", txtUsername.Text);
cmd.Parameters.AddWithValue("#passwrd", txtPassword.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
// cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new ApplicationException("!!! An Error Occurred While Inserting Record. " + ex.Message);
}
finally
{
da.Dispose();
cmd.Dispose();
Cnn.Close();
Cnn.Dispose();
}
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Login Successfully";
// da.Dispose();
// cmd.Dispose();
// Cnn.Close();
// Server.Transfer("Home.aspx");
Response.Redirect("PhotosettingsReport.aspx");
}
else
{
Msg.Text = "Login Failed";
}
}
}
}
Without seeing the code, it's impossible to even guess as to what object is throwing this error.
Run the website in Visual Studio in debug mode (F5), and put a breakpoint at btnLogin_Click. When you click the button, it will break and allow you to step into the code. Step through the code until you find the line that is throwing the exception - that is the object that is null.
You're either trying to access something declared in the method that has not been initialized, or an object outside the method that has not been initialized.
Stepping through the code will quickly show you what's wrong.
UPDATE
I'd check txtUserName and txtPassword to be sure they have values. Also, are you sure you're getting results into the ds.Tables[0]? Calling Rows.Count on ds.Tables[0] could also result in that error if there are no tables.
Also, check your Web.config file - make sure that "PhotostudioConnectionString" is spelled correctly, including the case of the letters.
Why are you checking for IsValid != null? I think if (!IsValid) would be more proper. IsValid will either be true or false, it will never be null, so your code will always pass that check.

Resources