While inserting new record into database, it is updating old record in grid view - asp.net

Grid view updating old record, when i'm trying to add new record.
In grid view I have a edit option. If I click on edit, the particular row is going to edit screen and filling textboxes and updating as expected. When clicking on add new record button in grid view, it is going to add screen with empty textboxes as expected, but if I add a new record, it is updating the previous record which was edited.
protected void GV_PRIOR_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int pid = Convert.ToInt32(GV_PRIOR.DataKeys[e.NewSelectedIndex].Value);
DataTable dt = bll.editprior(pid);
foreach (DataRow dr in dt.Rows)
{
HiddenField1.Value = dr["P_ID"].ToString();
tb_prioname.Text = dr["P_NAME"].ToString();
chk_actprior.Checked = dr["P_ACTIVE"].ToString() == "Y";
}
btn_savprior.Text = "UPDATE";
}
protected void btn_savprior_Click(object sender, EventArgs e)
{
if (HiddenField1.Value == "")
{
bll.savprior(0, tb_prioname.Text, Convert.ToBoolean(chk_actprior.Checked));
Response.Write("<script>alert('Priority Saved Successfully')</script>");
}
else
{
bll.savprior(Convert.ToInt16(HiddenField1.Value), tb_prioname.Text, Convert.ToBoolean(chk_actprior.Checked));
Response.Write("<script>alert('Priority Updated Successfully')</script>");
}
bindgrid();
}
If I click on the add new record button, after filling textboxes it should add a new record, but it is updating the old record which was edited just before adding new record.
Stored Procedure:
ALTER PROC [dbo].[SAVEPRIOR]
#P_ID int,
#P_NAME varchar(20),
#P_ACTIVE char(1)
AS
BEGIN
IF(#P_ID=0)
BEGIN
INSERT INTO PRIORITY(P_NAME) VALUES (#P_NAME)
END
ELSE
BEGIN
UPDATE PRIORITY SET P_NAME=#P_NAME,P_ACTIVE=#P_ACTIVE WHERE P_ID=#P_ID
END
END
DAL:
public void savePRIOR(int id, string priorname, bool actv )
{
SqlCommand cmd = new SqlCommand("SAVEPRIOR", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#P_ID", id);
cmd.Parameters.AddWithValue("#P_NAME", priorname);
cmd.Parameters.AddWithValue("#P_ACTIVE", (actv) ? "Y" : "N");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
BAL:
public void savprior(int id, string priorname, bool actv )
{
dll.savePRIOR(id, priorname, actv);
}

Try to clear the HiddenField1.Value="";
before bindgrid();

Related

ASP.NET DropdownList Always insert the first item

I have dropdownlist on my website. When I select the any item to insert the database but it does not insert selected item always insert the first item inside the dropdown list. Please Help How can I solve that problem?
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategory();
}
}
void GetCategory()
{
dlCategory.DataSource = Data.GetDataTable("SELECT * FROM tblCategory");
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}
SqlConnection baglanti = Data.baglan();
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values(#CategoryID)", baglanti);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
Your question is a bit blurry regarding the code, so correct me if I misunderstood, but I presume you want to do the following in WebForms:
Simply show all available categories that can be assigned to a
product
When the user selects the category and hits submit, it will be inserted to the DB assegnied to it
It is not quite elegant, but I would put something like this:
private SqlConnection _sqlConnection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
_sqlConnection.ConnectionString = #".." //Assign whatever your ConnectionString is in Data.baglan();
_sqlConnection.Open();
if (!IsPostBack)
{
GetCategory();
}
else
{
//Define your insert something like this, and I would put this into the submit Button_Click event:
if (!String.IsNullOrEmpty(dlCategory.SelectedValue) && dlCategory.SelectedValue != "0")
{
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values (#CategoryID)", _sqlConnection);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
}
else
{
//TODO: Handle wrong selection, eg display an error message..
}
}
}
void GetCategory()
{
dlCategory.DataSource = new SqlCommand("SELECT * FROM tblCategory", _sqlConnection).ExecuteReader();
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}

delete record from gridview but not from database

I am trying to delete record from grid but not from Database.
I want to set database field ISDeleted 1 when data deleted from gridview but don't want to delete record from db.
My code delete records from both gridview and db.
Where to change in my code-
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
}
}
public void fillLanguageGrid()
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
if (chkdelete.Checked)
{
string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
// command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
deleteRecordByName(name);
}
}
fillLanguageGrid();
}
public void deleteRecordByName(string Name)
{
SqlConnection sqlConnection = new SqlConnection(strcon);
using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
{
// define this to be a stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
// define the parameter and set its value
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#IsDeleted", SqlDbType.Bit)).Value = 1;
command.Parameters["#status"].Value = "Delete";
//open connection, execute DELETE query, close connection
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Dispose();
}
}
For that you need to add a column in your respective database table whether to show that record or not.For Ex: add column like Visible int.
Assume if
Visible =1 --> Show that record in gridview
Visible =0 --> Hide that record in gridview
By default make Visible =1 so all records are shown in gridview(write the query like Select ......Where Visible =1).when you try to delete record use update query that need to update Visible column 1 to 0.So your gridview only shows records where visible =1 .That particular deleted record is not shown in your gridview because its Visible column is 0.Try this..

selecting individual rows from gridview using check box

I have a gridview that contains a check box inside the template field. I want to retrieve the values of the rows where the check box is checked so I can update them through the database. Here's my code:
protected void approve_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked)
{
//I thought if the loop finds a checked check box, it will execute the following to that row:
con.Open();
string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";
SqlCommand scmapprove = new SqlCommand(approve, con);
scmapprove.ExecuteNonQuery();
view();
con.Close();
}
}
However, it doesn't seem to work. For example I checked five rows from the table, It only updates the first row. What should I do?
You are rebinding the Gridview after finding a checked row. Bind it after completing all update operations:
protected void approve_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked)
{
//I thought if the loop finds a checked check box, it will execute the following to that row:
con.Open();
string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";
SqlCommand scmapprove = new SqlCommand(approve, con);
scmapprove.ExecuteNonQuery();
//view(); //Donot rebind the gridview now.
con.Close();
}
}
view();
}

Asp.net markup file

I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..

Accessing User's specific data ASPX / .MDF table

I am using Visual studio and have the following page_load function on my Default.aspx web form:
if (IsPostBack == false)
{
//Display all records on the form load
DisplayCars("");
I have a user, where I can get their username (which I have used to add as the "Creator" of the specific data record). I want to use this username to only display cars where the username = ACar.Creator
How would I go about doing this? I have everything setup in order to do this.
I need something like the following:
if (User.Identity.Name == ACar.Creator) {
show this record
}
But I do not know the syntax for this within aspx/sql
Thanks
You should actually do this in the database by passing username
public DataTable GetUserRecord(string userName)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("connection string to database");
using(conn)
{
string sql = "SELECT car.CarName, car.Model FROM car WHERE car.Creator = #UserName";
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.AddWithValue("#UserName", userName);
dt.Load(comm.ExecuteReader());
}
return dt;
}
From your page
protected void Page_Load(object sender, Eventargs e)
{
DataTable dt = GetUserRecord(User.Identity.Name);
if(dt.Rows.Count > 0)
{
string firstRowCarName = dt.Rows[0]["CarName"];
//etc
}
}

Resources