Set focus on the repeated row data while typing duplicate value - asp.net

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

Related

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

In DropDown Selected_Indexchanged event SelectedValue is always getting reset in First Value

I have DropdownList which I populate at the time of Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select distinct sname from contacts where sname is not null";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
DropDownList2.DataSource = table;
DropDownList2.DataValueField = "sname";
DropDownList2.DataTextField = "sname";
DropDownList2.DataBind();
}
}
Now I am trying to populate a GridView when the DropDownList's Item changes
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string val = DropDownList2.SelectedValue;
string sqlQuery = "SELECT distinct DUTY_DATE FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE and SYSDATE+30 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL and contacts.sname = '" + val + "' ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
I have enabled the AutoPostBack. Now when I am changing a DropDownList item to a different one the Page is loading but always retaining the first value. I tried to debug , I found that
string val = DropDownList2.SelectedValue;
the val variable is always the first value that is returned by the Query. Can anybody please tell me how could I get rid of this. I want to populate the GridView whenever I am selecting any item in the dropdown.
Hi i think that dropdownlist charge again when you select other item. Put a Break Point in Page Load and look if your dropdownlist charge again i don't see other reason. Good Luck
Your Drop downlist should look like as following :
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
Make sure AutoPostBack is Set to TRUE.
One more thing you can try is to select the item when the index is greater than -1.
if(DropDownList2.SelectedIndex != -1)
{
string val = DropDownList2.SelectedItem.Value;
// enter code here
}

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

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

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();
}

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