How to implement editing Master/Detail records? - 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 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.

Related

Changes from datagridview not being saved in database

I have this form,when I give it some ID and click the highlighted button,shows me some info in a datagridview taken from a database.
First Form
The code of the button is here:
private void kerkoButton_Click(object sender, EventArgs e)
{
try
{
Konektimi();
string query = "SELECT * FROM Vizita WHERE PacientiId=#pacientiId";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#pacientiId",pacientiTextBox.Text);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
DataTable dt = new DataTable();
dt.Load(reader);
forma.vizitaDataGridView.DataSource = dt;
forma.ShowDialog();
}
else
{
MessageBox.Show("Nuk ka të dhëna për këtë pacient");
}
}
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Suposing that we get something from the database we get this:
Second Form,with the results
This is a new form that will be opened after clicking the kerkoButton.
NOW,the problem is this: When I edit a row(or some rows),if I click Save,the changes will not be saved in the database.
What should i do?
Could I make a SaveButton in this datagridform?If yes,how?
Take a look at "how to update row in DataGridView?"
You can access the edited row by using the property CurrentRow of your DataGridView like so:
DataRowView dataRowView = yourDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { dataRowView.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Vizita", con);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
Alternatively, if you want to update all edited rows at once, you have to create a flag and set it to true whenever you change a property using the PropertyChanged event.
When clicking "Save" you iterate through all rows and add the edited ones to rowsToUpdate.

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 IF statement using GridView

I am working on my first web project and I need help adding IF logic when using GridView. I have a page (CustomerListPage) that has a GridView item that displays a list of customers(rows) that can be clicked. Once the customer is clicked, the user is redirected to a page called "CustomerUsagePage" which shows the most recent record of this customer. This is what my GridView code looks like for my CustomerListPage:
if (GridView1.SelectedRow.RowIndex == 0)
{
//string selectedUser = GridView1.SelectedRow.Cells[0].ToString();
Response.Redirect("CustomerUsagePage.aspx?Customer_Name=" );
BindGridview();
}
The code for my CustomerUsagePage looks like this:
private void BindControlvalues()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.CustomerTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
Label4.Text = ds.Tables[0].Rows[0][1].ToString();
Label1.Text = ds.Tables[0].Rows[0][0].ToString();
Label2.Text = ds.Tables[0].Rows[0][3].ToString();
Label3.Text = ds.Tables[0].Rows[0][4].ToString();
}
My problem is that I can only add IF logic the page where my GridView is located. I would like to click on a customer and have his data appear on my CustomerUsagePage with an if statement. Is it possible? I know I can do this by adding a page per customer but I dont want to go down that route, it seems to tedious. Does anyone have any suggestions?
You can use GridView-FormView (Master/Detail) Control
Link : http://www.codeproject.com/Articles/16780/GridView-FormView-Master-Detail-Control.
Or you can use classic behavior with ItemCommand event
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = CustomersGridView.Rows[index];
.....//Adjust your Response
}
}

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