How to add data from one grid view to another grid view using a button Asp.net - asp.net

I'm attempting to add details from one gridview to another gridview on the same page; however I'm not see the gridview (not visible). Not sure exactly what is causing that because visible is set to true in properties window.
protected void btnAssign_Click(object sender, EventArgs e)
{
DataRow drow;
DataTable dt = SetDataTable();
drow = dt.NewRow();
//GridView1.Rows.Add(1);
int row = GridView1.Rows.Count - 1;
drow["Customer Name"] = GridView1.Rows[row].Cells[0].Text;
drow["Invoice #"] = GridView1.Rows[row].Cells[1].Text;
drow["Invoice Qty"] = GridView1.Rows[row].Cells[2].Text;
//drow["Salary"] = textBox4.Text.Trim();
dt.Rows.Add(drow);
BindGrid(dt);
btnDelete.Visible = true;
}
private DataTable SetDataTable()
{
DataTable dt = new DataTable();
try
{
DataColumn dcol = new DataColumn("Customer Name", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Invoice #", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Invoice Qty", typeof(System.String));
dt.Columns.Add(dcol);
}
catch (Exception ex)
{
}
return dt;
}
private void BindGrid(DataTable dt)
{
try
{
if (dt.Rows.Count > 0)
{
GridView2.DataSource = dt;
}
else { }
}
catch (Exception ex)
{
}
}

Related

asp.net clear row selection for Multiple Grid with Single Button Click

Hi Friends i have created a single asp.net page(c#) with multiple grid view to display records. I have multiple command button to show records in these grid.
I am using single button to clear the row selection in grid but it is not working.
Please help me...
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{
if (GridView1.Visible == true)
{
GridView1.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewSearch.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewState.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewDistrict.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewType.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewEmployee.SelectedIndex = -1;
}
}
//---------------------updating my question with new problem-------------
Now i am able to to clear the selection from row but facing new problem.......When i am clicking on show(to show results state wise) button it is showing results and also clearing the selection when clicking on clear selection button with no problems....but when i click on another show button(to show results district wise) to show results it is showing results but when i select the row and click on clear selection button it is showing both grid with records......please help how to hide state Grid when i am Clicking on Clear Selection Button while using District grid......i am posting the code which i am using on Button Click....
.......clear selection....Button click:
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{ GridView1.SelectedIndex = -1;
GridViewSearch.SelectedIndex = -1;
GridViewState.SelectedIndex = -1;
GridViewDistrict.SelectedIndex = -1;
GridViewType.SelectedIndex = -1;
GridViewEmployee.SelectedIndex = -1;
}
.......State Grid....Button click:
protected void btnState_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
//GridViewState.Visible = true;
GridViewDistrict.Visible = false;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlState.Text;
string strquery = "select * from tblAsset2 where v_State=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewState.DataSource = ds;
GridViewState.DataBind();
int rowCount = GridViewState.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewState.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewState.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
....................District Grid....Button click:
protected void btnDistrict_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
GridViewDistrict.Visible = false;
//GridViewDistrict.Visible = true;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlDistrict.Text;
string strquery = "select * from tblAsset2 where v_District=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewDistrict.DataSource = ds;
GridViewDistrict.DataBind();
int rowCount = GridViewDistrict.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewDistrict.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewDistrict.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
I resolved my problem and it may help someone else so i am posting it.. i have written wrong line:- GridViewState.Visible = true; // i have commented this line and error gone
protected void GridViewState_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewState.Visible = true; // i have commented this line and error gone
}

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

Gridview does not show SQL Server database records

I'm designing a web system for my fyp.
I use SqlDependency to get table change info from cache.
I used SqlDataAdapter, dataSet and gridview, but it doesn't show any result on screen.
Can you tell me where the problem is in my code?
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] == null)
{
gvshipOrders.DataSource = Cache["shipOrders"];
gvshipOrders.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
gvshipOrders.DataSource = ds;
gvshipOrders.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
I've found the problem,
public partial class OrderProccessing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string value = Session["email"].ToString();
Classes.AddAddress addcuid = new Classes.AddAddress(value);
txtstaffname.Text = addcuid.addStaffName().ToString();
txtstaffID.Text = addcuid.fetchStaffID().ToString();
}
}
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] != null)
{
myGrid.DataSource = Cache["ShipOrders"];
myGrid.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
myGrid.DataSource = ds;
myGrid.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
}

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources