Gridview is not updating after databind is called - c#

I have 3 gridviews in 3 different updatepanels, which i update them after RowCommand.
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
The weird thing is only GridView1_RowCommand can update all three gridview. GridView2_RowCommand using the same method but i cannot update the gridview.
Please help me.
Thanks in advance.
Here is the code for Rowcommand:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandName
if (e.CommandName != "SaveStartTime")
return;
int rowIndex = int.Parse(e.CommandArgument.ToString());
string id = GridView1.Rows[rowIndex].Cells[0].Text;
Label time = GridView1.Rows[rowIndex].Cells[4].FindControl("ActualTimeStart") as Label;
time.Text = DateTime.Now.ToString("HH:mm");
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = "Server=.\\SqlExpress;Database=CMOS;Trusted_Connection=True";
Cn.Open();
var Cm = Cn.CreateCommand();
string store = string.Format(#"UPDATE [ApprovedExitPass] SET ActualTimeStart = '{0}' WHERE Id='{1}'", time.Text, id);
SqlCommand cmd = new SqlCommand(store, Cn);
cmd.Parameters.AddWithValue("#ActualTimeStart", time.Text);
cmd.ExecuteNonQuery();
Cn.Close();
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
//check the commandName
if (e.CommandName != "SaveReturnTime")
return;
int rowIndex = int.Parse(e.CommandArgument.ToString());
string id = GridView2.Rows[rowIndex].Cells[0].Text;
Response.Write(id);
Label time = GridView2.Rows[rowIndex].Cells[4].FindControl("ActualTimeArrive") as Label;
time.Text = DateTime.Now.ToString("HH:mm");
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = "Server=.\\SqlExpress;Database=CMOS;Trusted_Connection=True";
Cn.Open();
var Cm = Cn.CreateCommand();
string store = string.Format(#"UPDATE [ApprovedExitPass] SET ActualTimeArrive = '{0}' WHERE Id='{1}'", time.Text, id);
SqlCommand cmd = new SqlCommand(store, Cn);
cmd.Parameters.AddWithValue("#ActualTimeArrive", time.Text);
cmd.ExecuteNonQuery();
Cn.Close();
GridView1.DataBind();
GridView2.DataBind();
GridView3.DataBind();
}

YES,gridview1_rowcommand will update all three because if you see the gridview1_rowcommand.in that method you are calling the databind of other two gridviews also . so now why this happening only while calling gridview1_rowcommand because you might be probably calling first grid row command or some other Issue.
SO probably Verify whether you getting value in Response.write(id)

Related

Stop updatting DetailsView based on IF condition

I have DetailsView with connected SqlDataSource and I want cancel updating row when my condition is true in OnRowUpdating event
I did this step but when condition is true DetailsView still at editing mode all I need to return to normal view if the condition is true
protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
// Iterates through the rows of the GridView control
foreach (DetailsViewRow row in DetailsView1.Rows)
{
// Selects the text from the TextBox
// which is inside the GridView control
// Selects the text from the DropDownList
// which is inside the GridView control
string dropDownListText = ((DropDownList)
row.FindControl("DropDownList12")).SelectedItem.Text;
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd2 = new SqlCommand();
conn.Open();
cmd2.CommandText = #"Select StatusID from ComplainMain Where TicketID=#tktid";
cmd2.Parameters.AddWithValue("#tktid", ticketid.tktid);
cmd2.Connection = conn;
SqlDataReader rdr = cmd2.ExecuteReader();
int status;
while (rdr.Read())
{
status = rdr.GetInt32(0);
if (status == 3)
{
Label18.Visible = true;
Label18.Text = "Can not Modify this Complaint as Ticket Closed refer to the Admin";
e.Cancel = true;
}
}
}
}
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Label18.Visible = false;
DetailsView1.ItemUpdating += new DetailsViewUpdateEventHandler(DetailsView1_ItemUpdating);
}
Use ChangeMode method on your DetailsView
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

Deleting a row from DataGridView and SQL Server database

I am trying to delete a row of data in DataGridView and SQL Server database. On the first click on the delete button it shows
MessageBox.Show("Record Deleted Successfully!");
but the selected row was not deleted in DataGridView and in the database.
This is my code:
private void PayratesDisplay()
{
con.Open();
DataTable dt = new DataTable();
adap = new SqlDataAdapter("select Membership AS [Membership Type], PerSession AS [Per Session], Discounted from tbl_payrates", con);
adap.Fill(dt);
dataGridView4.DataSource = dt;
con.Close();
}
// Clear Data
private void ClearData()
{
tbMemship.Text = "";
tbPerses.Text = "";
tbDisc.Text = "";
ID = 0;
}
private void btn_PRdel_Click(object sender, EventArgs e)
{
if (ID != 0)
{
con.Open();
cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE Membership = #Membership", con);
cmd.Parameters.AddWithValue("#Membership", ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
PayratesDisplay();
ClearData();
}
}
If I understand correctly, you are trying to delete the current row of the grid. Then the ID member is not needed and you can use something like this
private void btn_PRdel_Click(object sender, EventArgs e)
{
var row = dataGridView4.CurrentRow;
if (row == null) return;
var ID = row.Cells["Membership Type"].Value;
// The rest of the code (w/o the "if ID != 0")
}
Change your code like this
int r=cmd.ExecuteNonQuery();
con.Close();
if(r>0){MessageBox.Show("Record Deleted Successfully!");}

paging in gridview , 2nd page empty , gridview populated on a button click event

I have searched this problem and non of the answers have not solved My problem.
when user types a word a word and clicks a button a SqlDataAdapter searches the database and puts the results to a datatable which populates the gridview.
When enabling the paging in gridview only the first page of gridview shows data !
here is my code. This is where my data table is defined :
private DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Search_Click(object sender, EventArgs e)
{
kcestring.DataSource = #"localhost";
kcestring.InitialCatalog = "KCE";
kcestring.UserID = "sa";
kcestring.Password = "123";
SqlDataAdapter searchadap = newSqlDataAdapter("sp_GetDevicePropByDeviceName2", kcestring.ToString());
searchadap.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter categoryID = new SqlParameter("categoryID", SqlDbType.BigInt);
categoryID.Value = drp_SubCategories.SelectedValue;
searchadap.SelectCommand.Parameters.Add(categoryID);
DataTable dt = new DataTable();
searchadap.Fill(dt);
grv_Device.DataSource = dt;
grv_Device.DataBind();
}
protected void grv_Device_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Device.DataSource = dt;
grv_Device.PageIndex = e.NewPageIndex;
grv_Device.DataBind();
}
Just remove
DataTable dt = new DataTable();
before
searchadap.Fill(dt);
The reason is that you have defined two dt (One global and the other local to the event btn_Search_Click). On the btn_Search_Click event you are filling the local dt. grv_Device_PageIndexChanging event is not getting any rows because its accessing the global variable. Both are different variables.
the answer was to big foe a comment !
this is my page load it contains stuff which is used in other parts of program :
protected void Page_Load(object sender, EventArgs e)
{
btn_Edit.Enabled=false ;
lbl_error.Visible = false;
if (!Convert.ToBoolean(Session["logedin"]))
{
Response.Redirect("Default.aspx");
}
hiddenitems.Visible = false;
if (Page.IsPostBack)
{ btn_Search.Visible = true;
lbtn_advacedsearch.Visible = true;
drp_Property.Visible = true;
txt_pvalue.Visible = true;
Label5.Visible = true;
Label4.Visible = true;
}
img_Logo.Visible = false;
//imgLogo.Src = "pics/Manufacturer_Logo/selectmodel.jpg";
SqlConnectionStringBuilder kcestring = new SqlConnectionStringBuilder();
kcestring.DataSource = #"localhost";
kcestring.InitialCatalog = "KCE";
kcestring.UserID="sa";
kcestring.Password="123";
//kcestring.IntegratedSecurity = true;
SqlDataAdapter empper = new SqlDataAdapter("sp_GetEmployeepermissionsByID", kcestring.ToString());
SqlParameter employeeID = new SqlParameter("employeeID", SqlDbType.BigInt);
employeeID.Value = Session["employeeid"];
empper.SelectCommand.Parameters.Add(employeeID);
empper.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable da = new DataTable();
empper.Fill(da);
}
Use this code inside PageIndexChanging:
{
GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Requseted_movie ORDER BY [ID] DESC", con);
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);
GridView1.DataSource = DT1;
GridView1.DataBind();
}

No mapping exists from object type System.Web.UI.WebControls.GridViewRow to a known managed provider native type

I want to make a gridview that when I select a row, its values will be populated to another gridview and text boxes, but I am encountering the error above. When I click the row in the GridView2, nothing is happening and an error in the sqladapter occurs. Please help me to fix this code..
Here is my code:
c#
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand com = new SqlCommand("SELECT MRPNo, MRPType, MRPDate FROM MRP WHERE MRPNo = #mrpno",con);
com.Parameters.Add("#mrpno", GridView2.SelectedRow);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(dt);
DataRow row = dt.Rows[0];
txtMRPNo.Text = row["MRPNo"].ToString();
txtMRPDate.Text = row["MRPType"].ToString();
txtMRPDate.Text = row["MRPDate"].ToString();
GridView3.DataBind();
GridView1.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text,
};
e.Row.Cells[0].Controls.Add(selectButton);
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView2, "Select$" + e.Row.RowIndex);
}
}
}
You can not use GridView2.SelectedRow as an input to Parameters.Add(). Please refer to MSDN (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow(v=vs.110).aspx) and you will see why.

Master Detail in ASP.NET

I have two tables.
tbl_Request(PKRequestID, RequestCode) and tbl_Personnel(PKPersonID, PerosnelName FKRequestID)
FKrfequestID is a foreign key to tbl_request.
I have a grid view in Requests.aspx page that shows tbl_request records. There is a "New Item" button in this page too. When user clicks this button RequestInsert.aspx page opens. In this page user enters some data like RequestCode and hits the "Next" button and goes to Personel.aspx page which contains a gridview that shows the personnel who are related to the request. In this page user should define Personnel who are related to the request. When the whole process finishes user hits "save" button. Both tables will be update when user clicks on "save" button. How can I implement Personel.aspx page?
HERE IS AN APPROACH :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dttbl = new DataTable();
dttbl.Columns.Add("PKPersonID", System.Type.GetType("System.String"));
dttbl.Columns.Add("PerosnelName", System.Type.GetType("System.String"));
dttbl.Columns.Add("FKRequestID", System.Type.GetType("System.String"));
Session["MyDataTable"] = dttbl;
}
}
protected void btnok_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["PKPersonID"] = txtid.Text ;
row1["PerosnelName"] = txtname.Text;
row1["FKRequestID"] = Session["FKRequestID"];
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
DataTable t2 = (DataTable)Session["MyDataTable"];
SqlConnection con = new SqlConnection("connection_string"
using (SqlCommand command = con.CreateCommand())
{
//Here you are inserting values to tbl_Request
if (con.State == 0)
con.Open();
command.CommandText = #"INSERT INTO tbl_Request (PKRequestID,RequestCode) VALUES (#PKRequestID,#RequestCode)";
command.Parameters.AddWithValue("#PKRequestID", Session["PKRequestID"]);
command.Parameters.AddWithValue("#RequestCode", Session["RequestCode"]);
command.ExecuteNonQuery();
}
foreach (DataRow row in t2.Rows)
{
//Here you are inserting values to tbl_Personnel
using (SqlCommand command2 = con.CreateCommand())
{
if (con.State == 0)
con.Open();
command2.CommandText = #"INSERT INTO tbl_Personnel (PerosnelName, FKRequestID) VALUES ( #PerosnelName, #FKRequestID)";
command2.Parameters.AddWithValue("#PerosnelName", txtname.Text);
command2.Parameters.AddWithValue("#FKRequestID", Session["PKRequestID"]);
command2.ExecuteNonQuery();
}
}
}

Categories

Resources