I am trying to upload files to database but it is giving me an null exception error
Here is the error:
System.NullReferenceException: Object reference not set to an instance of an object.
Can anybody help me finding the error:
Here is aspx code
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name"/>
<asp:TemplateField ItemStyle-HorizontalAlign = "Center">
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Here is the code behind:
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class DatabaseDownload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
If your connection named as
<add name="DefaultConnection" ...
then you can obtain its value using same key (DefaultConnection)
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Now if for some reasons that db does not work (perhaps you delete the DB file, etc) you can try to fixe it by deleting DB. Do this from the command line. Open the "Developer Command Propmpt for VisualStudio" under your "Start/Programs menu->All Programs->Visual Studio 2012->Visual Studio Tools"
Run the following commands:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Now execute "update-database" command from package manager console and it will create database for you without any obstacles.
Related
i m trying to implement a gridview on a web application, using asp.net. I m encountering a problem when it comes to sorting my datagrid, by a method - and i d like to ask for advice. This is my .aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="GridViewDemo1.Employee" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
ID="grvEmployee"
runat="server"
AutoGenerateColumns="true"
BackColor="AliceBlue"
ForeColor="Goldenrod"
BorderColor="YellowGreen"
BorderStyle="Groove"
Width="70%"
CellPadding="3"
CellSpacing="2"
AllowSorting="True"
OnSorting="GridView1_Sorting"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true" ViewStateMode="Enabled">
<RowStyle
HorizontalAlign="Center">
</RowStyle>
<FooterStyle
ForeColor="#8C4510"
BackColor="#F7DFB5">
</FooterStyle>
<PagerStyle
ForeColor="#8C4510"
HorizontalAlign="Center">
</PagerStyle>
<HeaderStyle
ForeColor="White"
Font-Bold="True"
BackColor="#A55129">
</HeaderStyle>
</asp:GridView>
</div>
</form>
and this is the .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace GridViewDemo1
{
public partial class Employee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = "SELECT * from dbo.[User]";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
grvEmployee.DataSource = ds;
grvEmployee.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//dataTable.DefaultView.Sort = e.SortExpression;
//grvEmployee.DataSource = dataTable;
grvEmployee.DataBind();
}
}
}
This is my web.config connectionstring:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=xxxxxx;Initial Catalog=yyyyyyy;User ID=zzzzz;Password=xxxxxx;" providerName="System.Data.SqlClient" />
The gridview gets populated properly, i used to get the "fired event Sorting which wasn't handled." but now i simply get no response from trying to sort a column. Does this even work with auto-generated columns? Where can i specify a sort expression? (Ascending/Descending etc)?
You have to do the initial DataBinding only if !IsPostback not on every consecutive postback:
if(!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = "SELECT * from dbo.[User]";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
grvEmployee.DataSource = ds;
grvEmployee.DataBind();
}
In GridView1_Sorting you have to select the ordered data from the database and assign it to the grid's DataSource property, then call grvEmployee.DataBind():
GridView Sorting Sample:https://stackoverflow.com/a/6602125/284240
i have a table with field named PIMAGE And i can't show this field.
gridview named:dgw-
my problem is that the gridview do not show the image
my code:
protected void Page_Load(object sender, EventArgs e)
{
StorDataContext stor = new StorDataContext();
var res = (from r in stor.Products
where r.PID!=13
select new {
name=r.PName,date=System.DateTime.Now.ToString(),company=r.Company,price=r.Price,quantity=r.Quantity,color=r.Color,size=r.Size,weight=r.PWeight,
PImage = r.PID});
GridView1.Visible = true;
GridView1.DataSource = res.ToList();
GridView1.DataBind();
}
and may ashx
public class ShowImg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
Int32 pid;
if (context.Request.QueryString["getID"] != null)
{
pid = Convert.ToInt32(context.Request.QueryString["getID"]);
context.Response.ContentType = "image/jpeg";
Stream strm = GetImage(pid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
}
public Stream GetImage(int pid)
{
StorDataContext stor = new StorDataContext();
System.Data.Linq.Binary b = null;
byte[] ibyte = null;
Product product1 = stor.Products.First(p => p.PID == pid);
b = product1.PImage;
ibyte = b.ToArray();
return new MemoryStream((byte[])ibyte);
}
and aspx
<asp:TemplateField HeaderText="PImage">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/ShowImg.ashx?id=" + Eval("PImage") %>' />
</ItemTemplate>
</asp:TemplateField>
what's wrong?
use asp.net - sql server - linq
I'm assuming you mean you have an image field in the database.
There's lots of examples available on the net for this, here's one from the asp.net forums
The short version is, you would set the control
within the gridview to display the image. On the ImageField, you
would use the DataImageUrlField attribute to reference the name of the
field in the database that contains the binary image data. Also on
the ImageField, use the DataImageUrlFormatString to define a path
that, for example, points to an ASPX handler page and passes to it the
specific ID value from the DataImageUrlField.
The relevant line of code might look like this:
<asp:ImageField DataImageUrlField="MyImageID"
DataImageUrlFormatString="MyHandlerPage.aspx?theImageID={0}" /> A
complete example that uses this approach and shows you the code for
the handler page is at:
http://www.highoncoding.com/Articles/207_Displaying_Images_from_Database_in_GridView.aspx
or check out this one
public void ProcessRequest (HttpContext context) {
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
and the aspx code
<asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="200px" Height="200px"
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your page_load in aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
ad.Fill(dt);
}
GVImages.DataSource = dt;
GVImages.DataBind();
}
}
and finally your web.config
<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
<!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
...................
...................
I am trying to make a simple library database. I list the search results in a gridview, then i have a textbox and a button, user enters the isbn and clicks loan button. Then, if there is enough number of items (itemNumber>0) it is loaned by user. Here is the screenshot of user interface:
My question is, when user clicks loan button the loan may or may not be succesful. In both cases, i print a message indicating whether loan is succesful or not, and i also want the updated gridview to be displayed. The problem is, after pressing the loan button the gridview disappears and i just see the textbox, button and the message on the screen. How can i show the updated version of gridview after pressing loan button?
Here is the code file:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchResults.aspx.cs" Inherits="Pages_SearchResults" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ISBN" DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ISBN" HeaderText="ISBN" ReadOnly="True"
SortExpression="ISBN" />
<asp:BoundField DataField="AuthorName" HeaderText="AuthorName"
SortExpression="AuthorName" />
<asp:BoundField DataField="AuthorlName" HeaderText="AuthorlName"
SortExpression="AuthorlName" />
<asp:BoundField DataField="ItemType" HeaderText="ItemType"
SortExpression="ItemType" />
<asp:BoundField DataField="PublishYear" HeaderText="PublishYear"
SortExpression="PublishYear" />
<asp:BoundField DataField="numOfCopies" HeaderText="Number of Copies"
SortExpression="numOfCopies" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Items] WHERE ([Title] LIKE '%' + #Title + '%')">
<SelectParameters>
<asp:FormParameter FormField="tSearchBox" Name="Title" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server" Text="Type ISBN to loan:"></asp:Label>
And here is the .cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Pages_SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
Int32 verify;
string title = GridView1.HeaderRow.Cells[0].Text, isbn = GridView1.HeaderRow.Cells[1].Text, name = GridView1.HeaderRow.Cells[2].Text, lname = GridView1.HeaderRow.Cells[3].Text, type = GridView1.HeaderRow.Cells[4].Text, year = GridView1.HeaderRow.Cells[5].Text;
}
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
string numQuery = "select numOfCopies from Items where ISBN='" + tLoanBox.Text + "'";
SqlCommand cmdnumQuery = new SqlCommand(numQuery, con);
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
int num=Convert.ToInt32(cmdnumQuery.ExecuteScalar());
result = cmd2.ExecuteNonQuery();
if (num > 0)
{
if (result > 0)
Response.Redirect("LoanSuccesfull.aspx");
}
else
notAvailable.Visible = true;
con.Close();
}
}
And here is the code for loan button:
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
result = cmd2.ExecuteNonQuery();
if (result > 0)
{
loanSuccesful.Visible = true;
Response.Redirect("LoanSuccesfull.aspx");
}
con.Close();
}
I appreciate any help. Thanks
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
I was totally lost on why my Gridview.Databind() would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes is my GridView ID.
Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.
Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
GridView1.DataBind()
End Sub
I got the below code from internet. It is working properly. I have added paging also. When I'm just sorting, it is working properly. When I am changing the page index, the sorting is lost.
Here is the client side code that set a gridview with 20 items per page, using the sort linked to the "GridView1_Sorting" method in the server side code.
Client side
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now the server side code:
Server side
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{
case "ASC":
GVSortDirection = "DESC";
break;
//assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string sortDirection = GetSortDirection();
dataView.Sort = e.SortExpression + " " + sortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();
}
}
When you page, the PageIndexChanging event is called. This in turn runs the GridData() procedure, which sets the data source for the gridview to be a data table containing records from the emp table, with no particular sort order.
What you should do is to take the code that you've written in your GridView1_Sorting event-handler, and include this within the GridData routine, so that whenever the grid is populated with data - whether when the page first loads, when the page index is changed or when the gridview is sorted - the gridview is based on a sorted dataview, rather than an unsorted data table.
The way you are maintaining SortDirection using GetSortDirection, in same fashion maintain SortExpression.
Happy coding!!!
Have a look to this article, may you will get what you want
am using a gridview. When I click on the edit button the update and cancel button appear. Upon modifying the values in textbox which come from EditItemTemplate , the new values dont show in the event handler rowupdating(), instead I get the values which appear when the page was rendered. How do I grab the new values from these textboxes and proceed further? Here is the code.
aspx page
<%# Page Language="C#" MasterPageFile="~/Master Pages/FacultyMasterpage.master" AutoEventWireup="true" CodeFile="FacultyQuestion.aspx.cs" Inherits="Faculty_FacultyQuestion" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Content10" Runat="Server">
<br />
<br />
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
AllowPaging="True" AutoGenerateEditButton="True"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
<br />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content20" Runat="Server">
</asp:Content>
cs file coading
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Faculty_FacultyQuestion : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
private void BindData()
{
DataTable dt = Class3.QuestionForFaculty(Convert.ToInt32(Session["rid"]));
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
{
//Retrieve the table from the session object.
DataTable dt = Class3.QuestionForFaculty(Convert.ToInt32(Session["rid"]));
GridView1.DataSource = dt;
GridView1.DataBind();
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["ans"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
GridView1.EditIndex = -1;
BindData();
}
}
}
class 3 coading
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.ComponentModel;
[DataObject]
/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{
private static string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
[DataObjectMethod(DataObjectMethodType.Select)]
public static DataTable getall()
{
SqlDataAdapter dp = new SqlDataAdapter("Select * from Question", conn);
DataSet ds = new DataSet();
dp.Fill(ds, "Question");
return ds.Tables["Question"];
}
[DataObjectMethod(DataObjectMethodType.Delete)]
public static int delete(int qid)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Delete into Question qid = #a", con);
cmd.Parameters.Add("#a", SqlDbType.VarChar).Value = qid;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return(i);
}
[DataObjectMethod(DataObjectMethodType.Select)]
public static DataTable QuestionForFaculty(int rid)
{
SqlDataAdapter dp = new SqlDataAdapter("SELECT Question.question, Question.ans,Question.qid, Subject.subjectname, Question.posteddate, Registration.name, Registration.role, Registration.rid FROM Question INNER JOIN Registration ON Question.rid = Registration.rid INNER JOIN Subject ON Question.sid = Subject.subjectid WHERE (Question.fid = '"+rid+"')", conn);
DataSet ds = new DataSet();
dp.Fill(ds, "Question");
return ds.Tables["Question"];
}
}
Why are you databinding the GridView at the start of the OnRowUpdating event? That right there is your problem! Just remove this:
GridView1.DataSource = dt;
GridView1.DataBind();
UPDATE: first add this to your Class3 (purely based on your sample code - not tested):
[DataObjectMethod(DataObjectMethodType.Update)]
public static int UpdateAnswer(int qid, string ans)
{
var con = new SqlConnection(conn);
var cmd = new SqlCommand("UPDATE Question SET ans = #ans WHERE qid = #qid", con);
cmd.Parameters.Add("#qid", SqlDbType.VarChar).Value = qid;
cmd.Parameters.Add("#ans", SqlDbType.VarChar).Value = ans;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return(i);
}
Then change OnRowUpdating event to:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Class3.UpdateAnswer(row.DataItemIndex, ((TextBox)row.Cells[2].Controls[0]).Text);
GridView1.EditIndex = -1;
BindData();
}