how to get value of column in datgrid using asp.net c# - asp.net

here is code which is working. it is in loop which is deleting last row of data in grid but some how i am not able to pick the single row value for deleting particular selected row in Datagrid.
enter code here
String Name1;
protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
{
DataGridItem dataGridItem;
foreach (DataGridItem dataGridItem in DataGrid1.Items)
{
String Name = dataGridItem.Cells[2].Text;
Label1.Text = Name;
Name1=Name;
}
con.Open();
SqlCommand cmd = new SqlCommand("delete from salaryentry where levelnno='" + Name1 + "'", con);
cmd.ExecuteNonQuery();
con.Close();
databind();
}

use this to select row and print into text box and using delete command to delete the row:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
textBox1.Text = dataGridView1[0, e.RowIndex].Value.ToString();
}

Related

Asp.net Gridview row edit - How to remove select row event

Hi Friends wish you all Happy New Year 2017!
I am displaying records in grid and i have code to select the row and display records in text boxes as per selected row.
I have Edit Button to edit records in grid row but when i click on text box (edit mode) to enter value it is showing error because the "select row" event is still active.
Any help how to remove the select row action when edit button is clicked.
// click on the row to select and display records in text boxes
protected void gvUsrEdit_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvUsrEdit.SelectedRow;
Label l1 = row.FindControl("Label1") as Label;
Label l2 = row.FindControl("Label2") as Label;
i_TranInputID.Text = l1.Text;
tReason.Text = l11.Text;
gvUsrEdit.Visible = false;
}
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = e.NewEditIndex;
show1();
}
public void show1()
{
string strquery = "select * from btaprs2 where vEmpID=#d1 and vQuarter=#d2 and vyear1=#d3 and tKRA=#d4 and v10='Active' ";
con.Open();
SqlCommand cmd = new SqlCommand(strquery, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsrEdit.DataSource = ds;
gvUsrEdit.DataBind();
con.Close();
}
catch (Exception ex)
{
Response.Write(ex);
Label46.Text = "Error in page please check!";
}
}
You need to change the RowIndex.
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = -1;
show1();
}
I would suggest to Edit the rows this way:
You may want to use RowUpdating method like this:
protected void gvUsrEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
i_TranInputID.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label1") ).Text;
tReason.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label2")).Text;
tReason.Text = l11.Text;
gvUsrEdit.EditIndex = -1;
show1();
}

Set focus on the repeated row data while typing duplicate value

I have a gridview in asp.net, in which I am inserting datas. When I insert repeated value then it will show item repeated. Now I need to show after the item repeated alert message the cursor will focus on the row value contain the item which is repeated. If my data table already contain code C1, then I again type c1 for insert then the cursor will focus on the row which contain c1 in gridview. Here is my code
protected void Button15_Click(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string Code = (control.FindControl("txtcode") as TextBox).Text;
string txtno= (control.FindControl("txtno") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXXX;User ID=XXXX;Password=XXXXXX"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from tbltmp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
(control.FindControl("txtcode") as TextBox).Focus();
}
else
{
(control.FindControl("txtno") as TextBox).Focus();
}
}
}
}
set focus on the textbox as textbox1.focus in button event of repeated row checking

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..

asp.net gridview edit button doesn't update

When I enter new data and press update button it saves the old data (data that I want it to update).
public void fill()
{
SqlCommand cmd = new SqlCommand("select * from school ",con );
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
fill();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
string stu =((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int age = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
SqlCommand cmd = new SqlCommand("UPDATE school SET stu_name=#stu_name,age=#age where id=#id ", con);
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#stu_name", stu));
cmd.Parameters.Add(new SqlParameter ("#age",age));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fill();
}
he problem that the values that assigned to name,age are the existing values in the database not the new values which I entered in the runtime
any one can help me??
thanks in advance
You are repopulating the grid every time you edit it.
Call fill(); on grid init instead.
Here's some info on the Life Cycle of a web form. I think all you need is to wrap your fill(); in an if statement. Because page_load happens before your event handler, you reload from the db on top of the values that were entered.
if(!PostBack)
{
fill();
}

How to retrieve column values separately through sql data adapter class?

I am trying to learn how to use sql data adapter ... I have coded the following to check how it works ...
the problem is i want to retrieve values of 3 columns(DeptNo,DeptId,DeptName) of my database table "Sana" separately and display them in three separate text boxes ...
Through the code mentioned below I am able to retrieve the value of entire tuple of data base table together
what should I do to reach above mentioned result???
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select DeptNo,DeptId,DeptName from Sana where DeptName='" + TextBox1.Text + "'", connect);
SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
DataSet MyDataSet = new DataSet();
myAdapter.Fill(MyDataSet, "Departments");
object[] rowVals = new object[3];
foreach (DataTable myTable in MyDataSet.Tables)
{
foreach (DataRow myRow in myTable.Rows)
{
foreach (DataColumn myColumn in myTable.Columns)
{
Response.Write(myRow[myColumn] + "\t");
}
}
}
}
}
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
TextBox1.Text = myRow["DeptNo"].ToString();
TextBox2.Text = myRow["DeptId"].ToString();
...
}

Resources