Master Detail in ASP.NET - c#

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

Related

Gridview is not updating after databind is called

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)

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!");}

Data table in C#.net

I have a problem related to DataTable in .net.
i am trying to fill datatable on page_load .that part is ok no issue datatable correctly filled up with data. but I noticed that when I clicked button on page... it again try to fill datatable which just a time-consuming task... I want datatable should fill once only ,when , when site open in browser .. not at every click ... because I have a large amount of data in table so it takes time to load in datatable..
plz help me out ...
here is my code:
protectd void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
// if (this.IsPostBack == true)
{
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}
OleDbDataReader TableUtoPunj(String ArrWord)
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
}
cnn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "SELECT U, P from UtoP";
cmd.Connection = cnn;
OleDbDataReader dr = cmd.ExecuteReader();
return dr;
}
You need to check if the page is posting back or not, like this:
protected void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
if(!IsPostBack)
{
// This will only happen when the page is first loaded, as the first time is not considered a post back, but all others are
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}
Only fill the dataTable if it's not a PostBack...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//TO DO: Make the call to fill the data table here
}
}

How to implement editing Master/Detail records?

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 the code for personnelaspx.cs code:
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();
}
}
}
How can I implement edit mode? In this mode I want users be able to delete personnel or add them?
Ok. You need to use session to store the tbl_Request.PKRequestID of the record that is to be edited when user clicks Edit button. After that re direct the user to a new page Edit_Requests_Personnel.aspx where you can edit the records.

Categories

Resources