I have GridView. When I click a button, it sends data to another table and makes the previous GridView empty.
I have the following code for the button click, but it does not make the previous GridView empty.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string userApply = "insert into Company (CompanyName) select (JobTitle) from Jobs where JobTitle=JobTitle";
SqlCommand insertApply = new SqlCommand(userApply, conn);
try
{
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("ApplyJob.aspx");
}
catch (Exception er)
{
Response.Write(er.ToString());
}
finally
{
}
}
}
}
Are you clearing the previous gridview anywhere?
Maybe try this before your redirect:
grvPrevious.DataSource = null;
grvPrevious.DataBind();
it looks like you have your GridView in ApplyJob.aspx, since you are redirecting to that page in your try block and there you see the gridview holding some values. You may pass a query string along with ApplyJob.aspx and then in your form load of ApplyJob.aspx check for that query string. If you find the value then clear the Gridview. Something on the following line..
In your try block do :
Response.Redirect("ApplyJob.aspx?ClearGridView=YES");
In your Form_Load event of the ApplyJob.aspx check for the query string
if(Request.QueryString["ClearGridView"] != null && Request.QueryString["ClearGridView"] =="YES")
{
yourGridView.DataSource = null;
youGridView.DataBind();
}
Related
Edit 2: Turns out it only gives a NullReferenceException the first time. After that, it says that I am not allowed to change the ConnectionString property, even though I think I have closed it in the right places.
Thanks for taking the time to read this.
I am working on a WinForms application that uses an MS Access database, and I am currently having problems with an entry deletion feature I made.
So, I have a DataGridView that switches between 3 tables on a button click, and I have a function that deletes a row on a table that is currently open by clicking a button that is at the end of the row.
When I open my first table, and try to delete a row, it works just fine. However, if I open a different table afterwards and try to delete an entry, or even go back to the first table I opened, I get a NullReferenceException in the deletion function.
Here is the code to display one of the tables in DataGridView.
public DataTable Read()
{
connection.ConnectionString = connectionString;
OpenConnection(); //connection.Open() inside an if statement
dataTable.Clear();
OleDbCommand readStudentCommand = new OleDbCommand("select * from Students", connection); //display the whole list of students
OleDbDataReader reader = readStudentCommand.ExecuteReader();
dataTable.Load(reader);
connection.Close();
return dataTable;
}
Here is the code that deletes an entry
private void MainDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
connection.ConnectionString = connectionString;
if (ConnectionState.Closed == connection.State)
{
connection.Open();
}
var senderGrid = (DataGridView)sender;
if (e.RowIndex >= 0 && senderGrid.Columns[e.ColumnIndex] == MainDataGridView.Columns["Delete"])
{
//this function retrieves the first column value of the deleted row, which has the ID of the entry (works with any table).
DeleteEntry(MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()); //exception thrown here (System.Windows.Forms.DataGridViewCell.Value.get returned null)
MainDataGridView.Rows.RemoveAt(e.RowIndex);
}
and here is DeleteEntry()
private void DeleteEntry(string deletedID)
{
string tableName = null;
string idType = null;
if (studentsDisplayed)
{
tableName = "Students";
idType = "Student ID";
}
else if(booksDisplayed)
{
tableName = "Books";
idType = "BookID";
}
else if(loansDisplayed)
{
tableName = "Loans";
idType = "Loan ID";
}
string deleteCommand = String.Format("DELETE * FROM {0} WHERE [{1}] = {2}", tableName, idType, deletedID);
OleDbCommand deleteEntryCommand = new OleDbCommand(deleteCommand, connection);
deleteEntryCommand.ExecuteNonQuery();
SaveData(); //this method just calls Update() in a dataAdapter of a relevant table
connection.Close();
}
Thank you!
Edit:
As per request, here is the code that switches the table. It simply references the first function and sets the returned dataTable as DataSource.
private void StudentButton_Click(object sender, EventArgs e) //display students
{
try
{
if (!studentsDisplayed)
{
MainDataGridView.DataSource = studentDAL.Read(); //studentDAL is the class that works with the Students table of my DB.
studentsDisplayed = true; //these 3 are to avoid duplicated creation of the same table
booksDisplayed = false;
loansDisplayed = false;
ComboBoxChanger(); //don't mind this, it's for an irrelevant feature
CreateButtons(5);
}
}
catch
{
throw;
}
}
Okay, so turns out the problem was the fact that DeleteEntry(MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()) had a problem with the Cells[0] part. After the first time loading a table, the 0th cell just vanished. So, I rewrote the code so that instead of declaring tableName and idType in DeleteEntry(), they're declared in MainDataGridView_CellContentClick(), and then made the DeleteEntry() accept 3 idType and tableName as parameters, and changed the MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString() argument to MainDataGridView.Rows[e.RowIndex].Cells[idType].Value.ToString(). Now it works just fine!
I have a drop down list of categories that is databound. The selection from this populates a gridview. When I delete a category, it is successfully updating my gridview of products (showing no entries), but not he dropdownlist of categories until I re-run the program.
My page load:
protected void Page_Load(object sender, EventArgs e)
{
// Check if loaded for first time.
if (!IsPostBack)
{
// Bind the data displayed in the Dropdownlists.
Login.SelectAllCat(DropListCat);
}
}
My code to delete a category:
protected void BtnDeleteCat_Click(object sender, EventArgs e)
{
try
{
// Get int id from selectioin in drop down list.
int id = Convert.ToInt32(DropListCat.SelectedValue.ToString());
// Call method to open data base, create command from stored procedure and delete item to database.
Login.DeleteCategory(id);
// Update the data displayed in the Dropdownlists.
Login.SelectAllCat(DropListCat);
}
catch (NullReferenceException)
{
LblProdId.Text = "No Category Selected!";
}
}
My dropdownlist:
<asp:DropDownList ID="DropListCat" runat="server" BackColor="#66FFFF"
Width="200px" AutoPostBack="True" AppendDataBoundItems="True">
</asp:DropDownList>
My connection and binding code. In Login class.
// Method to select all categories and display them in dropdown lists.
public static void SelectAllCat(DropDownList list)
{
// SqlConnection.
SqlConnection con = new SqlConnection(conString);
// Create new command and parameterise.
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SelectAllCat";
//
// Adapted from
// Source link: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/data-binding-to-dropdownlist-and-listbox-in-Asp-Net/
//
cmd.Connection = con;
try
{
// Open connection and bind data to GUI.
con.Open();
list.DataSource = cmd.ExecuteReader();
list.DataTextField = "CatName";
list.DataValueField = "CatID";
list.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
My stored procedure:
CREATE PROCEDURE SelectAllProd
AS
SELECT * FROM Prod;
GO
This is the result after I have attempted to delete a category.
When I re-run the project, the category will have been deleted.
Edit
Actually, it is deleting the category, but it's retaining the original data binding from page load. So I guess I need to work out how to wipe that.
Write
DropListCat.DataBind();
in BtnDeleteCat_Click
I fixed it by clearing the drop down list items before re-binding the data, as so:
// Method to select all categories and display them in dropdown lists.
public static void SelectAllCat(DropDownList list)
{
// Clear any previously bound items.
list.Items.Clear();
// etc.../
I am having trouble with a particular situation. The values in my dropdownlist are as follows: 101, 102, 103, but at any point in time the use can add or deactivate items to the dropdown ex: 101, 104, 106.
I have this dropdownlist embedded into a listview edit item template. So if the user adds a record with value 102, then later on deletes this value they cannot edit this value because I get the above error.
So what I am trying to figure out is how I can handle this message to let the use know they cannot edit the record. What I have so far is the ListView_ItemEditing event handler:
protected void LV_Equipment_ItemEditing(object sender, ListViewEditEventArgs e)
{
LV_Equipment.EditIndex = e.NewEditIndex;
e.Cancel = true;
try
{
LV_Equipment.DataBind();
}
catch (Exception ex)
{
//This is telling the user they cannot edit the record.
AlertMessage("you cannot edit this record.");
}
DropDownList UnitIDDDL = (DropDownList)(LV_Equipment.EditItem.FindControl("DropDownList1"));
DropDownList DriverIDDDL = (DropDownList)(LV_Equipment.EditItem.FindControl("DDL_Insert_Drivers"));
//We need to get the driver for the selected unit in the listview.
int ID = DatabaseInteraction.GetUnitDriver(UnitIDDDL.SelectedValue);
//Now that we have the id we can set the ddl.
DriverIDDDL.SelectedValue = ID.ToString();
DriverIDDDL.DataBind();
}
So if the user tries to edit a valid item there is no problem. But if they try to edit a deactivated item from the listview they LV_Equipment.DataBind() method will fail, and the rest of the code will throw an error as the UnitIDDDL and DriverIDDDL are set as null.
Any ideas on how to make this workaround effective?
Ok, here's what you need to do.
Your data binding should be coming from a SQL query of some sort. Let's assume it looks something like this:
string query = "SELECT ItemNumber FROM TableName";
SqlConnection conn;
SqlDataAdapter da = new SqlDataAdapter(query,conn);
DataTable sqlTable = new DataTable("Test");
da.Fill(sqlTable);
LV_Equipment.DataSource = sqlTable;
What you'll want to do is change your query so that it looks something like this:
string query = "SELECT ItemNumber FROM TableName WHERE Active = 'True'";
That should solve your problem.
Add a return to your catch block:
try
{
LV_Equipment.DataBind();
}
catch (Exception ex)
{
//This is telling the user they cannot edit the record.
AlertMessage("you cannot edit this record.");
return; // don't continue to process
}
I have two dropdownlists, ddlstates and ddlcitys.
The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?
In code behind, have code that loads the ddlcitys:
protected void ddlstates_TextChanged(object sender, EventArgs e)
{
if (ddlstates.Text != "")
{
List<ListItem> cidades = new List<ListItem>();
SqlConnection conn = new SqlConnection(mytools.stringconection);
SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
cmd.Connection = conn;
dr = cmd.ExecuteReader();
ddlcitys.Items.Clear();
while (dr.Read())
{
cidades.Add(new ListItem(dr[0].ToString()));
}
dr.Close();
conn.Close();
ddlcitys.DataTextField = "Text";
ddlcitys.DataValueField = "Value";
ddlcitys.DataSource = cidades;
ddlcitys.DataBind();
}
}
Asked long time ago, anyway may the answer help anyone.
On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.
hint : make sure that your aspx page enable view state (by default enabled) read more.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//this will called when your page loaded at first time, so bind your drop down values here.
} else {
//this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate).
}
}
I am facing a peculiar issue in my ADO.NET code. This is the table data that I am accessing from a repeater from the frontend.
1 get car cleaned 2012-02-14 08:32:25.643 NULL
2 submit tax documents 2012-02-14 08:33:04.610 NULL
3 photo copy all documents 2012-02-14 08:33:04.610 NULL
Data in the first row is not being displayed at all.
If I delete the rows 2 and 3, no data is being displayed in the repeater. I think the issue is with my ADO.NET code. Also, if I truncate the table completely, the page is loading forever as opposed to displaying the "No Data Found" message in the label.
protected void Page_Load(object sender, EventArgs e)
{
txtNewTask.Focus();
if (!IsPostBack)
{
GetTaskList();
}
}
protected void GetTaskList()
{
conn = new SqlConnection(cstr);
getTasksCmd = new SqlCommand("select Name, CreationDate, CompletionDate from tasks", conn);
try
{
using (conn)
{
conn.Open();
using (reader = getTasksCmd.ExecuteReader())
{
while (!reader.Read())
{
lblDbMsg.Text = "No Data Found!";
}
rptTaskList.DataSource = reader;
rptTaskList.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
Take out the while loop from your code:
using (reader = getTasksCmd.ExecuteReader())
{
rptTaskList.DataSource = reader;
rptTaskList.DataBind();
}
Because you are calling SqlDataReader.Read() once, you are moving past the first record. Therefore, if you want to be able to retrieve all of the rows of data including the first, don't call Read() at all.
SqlDataReader.Read() Method MSDN Reference