Object reference not set to an instance of an object in gridview in asp.net - asp.net

I am getting this error on a row command in my gridview. Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [CourseCode], [CourseNumber], [CourseName], [CRN], [Level], [Credit] from CourseTable where Term='" + MyGlobals.currentTerm + " " + MyGlobals.currentYear + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
gCourses.DataSource = tab;
gCourses.DataBind();
}
}
protected void gCourses_RowCommand(object sender, GridViewCommandEventArgs e)
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = gCourses.Rows[row];
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
string crn = dr["CRN"].ToString();
}
.
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
line throws the exception.
What is wrong here? Thanks

Remove the
if (!isPostback)
from your page load

Related

!IsPostBack returns always true

I am trying to implement search operation for my gridview.When I load my page first time !IsPostBack works fine but when I click on the search button my page loads again and !IsPostBack returns true value.So, I was not able to perform my search operation
this is my code.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
((Label)Master.FindControl("Label1")).Text = (string)Session["sname"];
fillData();
}
}
public void fillData()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
fillData();
}
protected void search_Click(object sender, EventArgs e)
{
string id = txtid.Text;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " and SupplierId='" + id + "' ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
I have found the solution myself I have a form control on my master page.I removed that it helped me.I thank you all for giving time to my question.

lable is not showing any output for the dropdown list selection

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbookavail.Items.Add(new ListItem("select", "-1"));
ddlbookavail.AppendDataBoundItems = true;
SqlCommand cmd = new SqlCommand("select * from tblbookinfo", con);
con.Open();
ddlbookavail.DataSource = cmd.ExecuteReader();
ddlbookavail.DataTextField = "Name";
ddlbookavail.DataValueField = "Id";
ddlbookavail.DataBind();
con.Close();
txtdate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
}
in my design page i put the sql datasource from data and got this connection srting

Making code duplication to refresh the gridview in asp.net

I am trying to update the gridview after updating some data. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = studentLevel.Rows[row];
DataRow dr = ((DataTable)studentLevel.DataSource).Rows[gdrow.DataItemIndex];
string id = dr["ID"].ToString();
Student student = new Student(Convert.ToInt32(id), "", "", "", "", "", "", "");
if (e.CommandName == "Undergraduate")
student.setLevelRole(new UnderGraduateStudent());
else if (e.CommandName == "Graduate")
student.setLevelRole(new GraduateStudent());
student.writeLevelRole(id);
SqlConnection con = new SqlConnection(); //HERE IS DUPLICATION
//refresh the gridview on the page
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
The problem is, if i do not write the last 12 lines of the code, which is the same code as page_load method, the gridview does not refresh itself on the page. Waht can i do to avoid this?
Thanks
You should provide a method that loads the data and databinds the GridView, for example DataBindGrid:
private void DataBindGrid()
{
using(var con = new SqlConnection(University.GetConnectionString()))
{
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
}
}
Then you can call it from wherever you need. If you want to change something you have only one place to maintain which is less error-prone.
Note that you should databind the GridView only if(!IsPostBack) if you use ViewState(default):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback))
DataBindGridView();
}
and in RowCommand
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ... update student ... then
DataBindGridView();
}

Gridview does not view the results in asp.net

I am trying to show the search results on a gridview on the same search page in asp.net. Here is the UI:
And here is my code:
protected void Page_Load(object sender, EventArgs e)
{
searchResults.DataBind();
}
protected void BClassSearch_Click(object sender, EventArgs e)
{
// if (!IsPostBack)
//{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string selected = lbCourseListBox.SelectedValue;
if(selected!="" && Tcoursenumber.Text!="")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue+"' and CourseNumber = '" + Tcoursenumber.Text+"'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected != "" && Tcoursenumber.Text == "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected == "" && Tcoursenumber.Text != "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseNumber='" + Tcoursenumber.Text;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
//}
Response.Redirect("SearchCourse.aspx");
}
The problem is, no search result is displayed in gridview. Can anyone help me with this?
Thanks
Remove Response.Redirect("SearchCourse.aspx"); at the end of button click
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do you want to bind something in first time load? then load it here
// searchResults.DataSource = tab;
searchResults.DataBind();
}
}
You don't want to call the Response.Redirect to the same page because when you click on button it will postback the page. if you call Response.Redirect it will load new page and you will lost all the control states in the page.

Grid view Updatearguments does Not contain New Values

public partial class Gridvw_expt2 : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
com = new SqlCommand("Select * from tblExpt",con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows[0] != null)
{
GridView1.AutoGenerateEditButton = true;
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
}
else
Response.Write("fkj");
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
foreach (DictionaryEntry entry in e.NewValues)
{
e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
}
com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
da = new SqlDataAdapter(com);
GridView1.EditIndex = -1;
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
In the above code when i try to access e.new values index out of range exception is thrown.
The table being accessed contains 3 fields id, class, name
Please help to solve the problem.
Read this blog post I wrote on extracting data from gridview (and other data controls). Also, in .net 4.0 if you use 2 way binding (<# Bind("") #>) e.NewValues will be populated.
More info here: http://weblogs.asp.net/davidfowler/archive/2008/12/12/getting-your-data-out-of-the-data-controls.aspx
The exception you get is because row.Cells[0].Controls[0] is a DataControlLinkButton and not a TextBox. Since I donĀ“t know the control layout of your grid you could search for your textbox instead.
Instead of:
int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);
do something like the code below if there is only one TextBox per row:
TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );
If you have nested html and hierarchies check out this SO question for nested searching of controls

Resources