Somebody please help me how to store the value dynamically using arraylist.Every time i want to add patient details. Here is my code layer wise:
PatientDataLayer:
public class PatientData
{
public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
public int AddPatient(Patient obj)
{
using (var con = new SqlConnection(str))
{
using (var com = new SqlCommand("AddPatient", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", obj.Name);
com.Parameters.AddWithValue("#Address", obj.Address);
com.Parameters.AddWithValue("#DateOfBirth", obj.DateOfBirth);
com.Parameters.AddWithValue("#Phone", obj.Phone);
com.Parameters.AddWithValue("#EmergencyContact", obj.EmergencyContact);
com.Parameters.AddWithValue("#DateOfRegistration", obj.DateOfRegistration);
con.Open();
com.ExecuteNonQuery();
con.Close();
return 0;
}
}
}
PatientBusinessLayer:
public class PatientBusiness
{
public void Add(Patient obj)
{
PatientData pd = new PatientData();
pd.AddPatient(obj);
}
}
Patient.aspx.cs:
protected void BtnAdd_Click(object sender, EventArgs e)
{
if (!Page.IsValid) //validating the page
return;
string name = TxtName.Text;
string address = TxtAddress.Text;
DateTime dateofbirth =Convert.ToDateTime(TxtDateOfBirth.Text);
int phone = Convert.ToInt32(TxtPhone.Text);
int emergencyno=Convert.ToInt32(TxtContact.Text);
DateTime registrationdate =Convert.ToDateTime(TxtRegistrationDate.Text);
PatientBusiness PB = new PatientBusiness();
Patient obj = new Patient();
try
{
obj.Name = name;
obj.Address = address;
obj.DateOfBirth = dateofbirth;
obj.Phone = phone;
obj.EmergencyContact = emergencyno;
obj.DateOfRegistration = registrationdate;
PB.Add(obj);
LblMessage.Text = "Patient has been added successfully";
TxtName.Text = "";
TxtAddress.Text = "";
TxtDateOfBirth.Text = "";
TxtPhone.Text = "";
TxtContact.Text = "";
TxtRegistrationDate.Text = "";
}
catch (Exception ee)
{
LblMessage.Text = ee.Message.ToString();
}
finally
{
PB = null;
}
}
Thanks,
Masum
I don't understand your question but after reviewing your code, I can only recommand you to consider using an ObjectDataSource combined with a FormView and stop doing "business stuff" in code behind.
Related
I have inserted an image on the 1st form namely Add_Staff and want to get that image on the 2nd form namely Staff_Detail's data gridview. how I can pass reference of add_staff images to staff_detail form's data gridview. Here is the code.
Insertion Code: -
private void BTNSTAFF_Click(object sender, EventArgs e)
{
if (staffid.Text == "")
{
if (teachername.Text == "" || saddress.Text == "" || semail.Text == "" || contact.Text == "" || jobspeciality.Text == "")
{
MessageBox.Show("All Fields Required");
}
else
{
Image pimg = pictureBox1.Image;
ImageConverter converter = new ImageConverter();
var ImageConvert = converter.ConvertTo(pimg, typeof(byte[]));
conn.Open();
//Values Inserted into Course
SqlCommand cmd = new SqlCommand("insert into staff values (#a,#b,#c,#d,#e,#g)", conn);
cmd.Parameters.AddWithValue("#a", teachername.Text);
cmd.Parameters.AddWithValue("#b", saddress.Text);
cmd.Parameters.AddWithValue("#c", semail.Text);
cmd.Parameters.AddWithValue("#d", contact.Text);
cmd.Parameters.AddWithValue("#e", jobspeciality.Text);
cmd.Parameters.AddWithValue("#g", ImageConvert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
frm1.RefreshGrid();
conn.Close();
Staff_Clear();
this.Hide();
}
}}
Staff Detail Code for View Deatil: -
public partial class Staff_Detail : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mudas\source\repos\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
public static string column_id = "";
public static string column_name = "";
public static string column_address = "";
public static string column_email = "";
public static string column_contact = "";
public static string column_job = "";
public Staff_Detail()
{
InitializeComponent();
View();
}
public void View()
{
try
{
dataGridView4.Rows.Clear();
// if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From staff", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String column_getid = dr["id"].ToString();
String column_getname = dr["name"].ToString();
String column_getaddress = dr["address"].ToString();
String column_getemail = dr["email"].ToString();
String column_getcontact = dr["contact"].ToString();
String column_getjob = dr["job"].ToString();
dataGridView4.Rows.Add(column_getid, column_getname, column_getaddress, column_getemail, column_getcontact, column_getjob, "Edit/Delet");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = dataGridView4.CurrentCell.RowIndex;
String Column_id = dataGridView4.Rows[rowIndex].Cells[0].Value.ToString();
String Column_name = dataGridView4.Rows[rowIndex].Cells[1].Value.ToString();
String Column_address = dataGridView4.Rows[rowIndex].Cells[2].Value.ToString();
String Column_email = dataGridView4.Rows[rowIndex].Cells[3].Value.ToString();
String Column_contact = dataGridView4.Rows[rowIndex].Cells[4].Value.ToString();
String Column_job = dataGridView4.Rows[rowIndex].Cells[5].Value.ToString();
column_id = Column_id;
column_name = Column_name;
column_address = Column_address;
column_email = Column_email;
column_contact = Column_contact;
column_job = Column_job;
Add_Staff ad = new Add_Staff(this);
ad.Show();
ad.BringToFront();
}
}
It only can be called once. where did I gone wrong? The second time it executes, no text appears. The Login and Site.Master are two different partial classes. I am kind of confounded on how to solve this.
Login.aspx
public partial class Login : System.Web.UI.Page
{
SqlDataReader dR;
DatabaseMgmt drObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
string strEmail, strPwd;
int intShopperID;
strEmail = txtEmail.Text.ToLower();
strPwd = txtPwd.Text.Trim();
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email ="+ "'" + strEmail + "'" + "AND Passwd ="+ "'"+ strPwd + "'";
dR = drObj.ExecuteSelect(strSqlCmd);
if(dR.Read())
{
intShopperID = Convert.ToInt32(Session["ShopperID"]);
Session["ShopperID"]=intShopperID;
Response.Redirect("Default.aspx");
}
else
{
intShopperID = 0;
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
dR.Close();
}
}
Site.Master
public partial class Site : System.Web.UI.MasterPage
{
DatabaseMgmt dBObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ShopperID"] != null)
{
string strSqlCmd;
strSqlCmd = "SELECT Name FROM Shopper WHERE ShopperID = " + Session["ShopperID"];
lblWelcome.Text = "Welcome Eric";
logoutButton.Visible = true;
loginButton.Visible = false;
regButton.Visible = false;
}
else
{
logoutButton.Visible = false;
loginButton.Visible = true;
regButton.Visible = true;
lblWelcome.Text = "";
}
}
Display Welcome Message
First Run
Second Run
database
I did not see where you are reading the ShopperID from the database. Perhaps that is your issue. ???
To address the Parameterisation issue, I think you should consider something more like this:
public int GetShopperID(System.String strEmail, System.String strPwd) {
int result = 0;
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email = #Email AND Passwd = #Passwd";
using (var cmd = new System.Data.SqlClient.SqlCommand(strSqlCmd, new System.Data.SqlClient.SqlConnection(_databaseConnection))) {
cmd.Parameters.Add("#Email", System.Data.SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Passwd", System.Data.SqlDbType.VarChar, 50);
cmd.Parameter["#Email"].Value = strEmail;
cmd.Parameter["#Passwd"].Value = strPwd;
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) {
result = Convert.ToInt32(reader["ShopperID"]);
}
}
}
return result;
}
First, it appears you close your connection, however you don't have an explicit open connection (unless you didn't include that line by mistake) which on a postback your query won't produce results since the connection is closed after you run it the first time. Second, confirm you don't have your code in a !Page.IsPostBack, which could also cause it not to appear. Finally you can do all that you are trying to do using one datareader instead of opening up two datareaders with this:
string strEmail = txtEmail.Text.ToLower();
string strPwd = txtPwd.Text.Trim();
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ShopperID, Name FROM Shopper WHERE Email = #Email AND Passwrd = #Passwrd", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Email", strEmail);
cmd.Parameters.AddWithValue("#user_name", strPwd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(dr["ShopperID"].ToString() != Session["ShopperID"].ToString())
{
Response.Redirect("~/default.aspx");
}
else if (dr["ShopperID"].ToString() == Session["ShopperID"].ToString())
{
lblWelcome.Text = "Welcome " + dr["Name"].ToString();
}
else
{
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
con.Close();
}
}
This also addresses the SQL injection by using Type-Safe SQL Parameters, which was outlined as an issue in other comments.
This is my insert statement. Records are not inserting but no errors showing also. Please help
protected void btn_Add_Click(object sender, EventArgs e)
{
if (btn_Add.Text == "Submit")
{
string Height = txtHeight.Text;
string TopDia = Convert.ToString(txtTopDiaMeter.Text);
string BottomDia = Convert.ToString(txtBottomDiaMeter.Text);
string ShaftThick = Convert.ToString(txtShaftThick.Text);
string BlackWt = Convert.ToString(txtBlackWeight.Text);
string TotManHrPerPole = Convert.ToString(txtTotManHrPoleData.Text);
string Plate_Length = Convert.ToString(txtPlateLength.Text);
string PLATE_DIA = Convert.ToString(txtPlateDia.Text);
string PLATE_THICKNESS = Convert.ToString(txtPlateThick.Text);
System.Collections.Hashtable ht = (System.Collections.Hashtable)Session["UserDetails"];
Int64 UsrId = (Int64)ht["UserID"];
string CreatedBy = Convert.ToString(UsrId);
string FoundBoltId = Convert.ToString(ddlFoundationBolt.SelectedValue);
string PoleTypeId = Convert.ToString(ddlPoltype.SelectedValue);
string ProductTypeID = Convert.ToString(ddlPdtType.SelectedValue);
string Status = chkActive.Checked ? "True" : "False";
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("~/Images/Pole Data/" + filename));
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["valmont"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Insert into DEF_POLE_DATA_MST(Height,TopDia,BottomDia,ShaftThick,BlackWt,TotManHrPerPole,Plate_Length,PLATE_DIA,PLATE_THICKNESS,CreatedBy,FoundBoltId,PoleTypeID,ProductTypeID,Status,ImagePath) values(#Height,#TopDia,#BottomDia,#ShaftThick,#BlackWt,#TotManHrPerPole,#Plate_Length,#PLATE_DIA,#PLATE_THICKNESS,#CreatedBy,#FoundBoltId,#PoleTypeId,#ProductTypeID,#Status,#ImagePath)", con);
cmd.Parameters.AddWithValue("#Height", Height);
cmd.Parameters.AddWithValue("#TopDia", TopDia);
cmd.Parameters.AddWithValue("#BottomDia", BottomDia);
cmd.Parameters.AddWithValue("#ShaftThick", ShaftThick);
cmd.Parameters.AddWithValue("#BlackWt", BlackWt);
cmd.Parameters.AddWithValue("#TotManHrPerPole", TotManHrPerPole);
cmd.Parameters.AddWithValue("#Plate_Length", Plate_Length);
cmd.Parameters.AddWithValue("#PLATE_DIA", PLATE_DIA);
cmd.Parameters.AddWithValue("#PLATE_THICKNESS", PLATE_THICKNESS);
cmd.Parameters.AddWithValue("#CreatedBy", CreatedBy);
cmd.Parameters.AddWithValue("#FoundBoltId", FoundBoltId);
cmd.Parameters.AddWithValue("#PoleTypeId", PoleTypeId);
cmd.Parameters.AddWithValue("#ProductTypeID", ProductTypeID);
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#ImagePath", "~/Images/Pole Data/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
Accordian.SelectedIndex = 1;
JQUERYDisplay.ShowAlertMessage("Record Inserted Successfully");
CleraFields();
}
catch (Exception ex)
{
JQUERYDisplay.ShowAlertMessage(ex.Message);
}
finally
{
}
}
Here's the table:
I have problem with button click event and post back. I have a page with some textboxes and some drop-down lists. I fill those textboxes and ddls from database. I also have 2 buttons. One of them is updating database with changed data from textboxes and drop-down lists. Second button is displaying additional data depending on value from one of the drop-down list. My problem is that when I click update button the database is updated and data in textboxes and ddls are changed but when I enter into address tab and push Enter I got old data (In database everything is changed into new values). I could add method to
if (IsPostBack)
and data will be always fresh but in that case I will not be able to change value in one of the drop down list which displays additional data (Auto post back will load data into this ddl). Is there any workaround to this? If my description is not clear, please let me know.
EDIT1 Adding C# code
public partial class EditStaff : System.Web.UI.Page
{
Methods methods = new Methods();
IPrincipal p = HttpContext.Current.User;
protected void Page_Load(object sender, EventArgs e)
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
if (!IsPostBack)
{
GetDDLsItems();
FillFields();
}
else
{
//FillFields();
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string update_error = "";
string SOEID = txtSOEID.Text;
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
string email = txtEmail.Text.Trim();
int remsCode = Convert.ToInt32(ddlREMS.SelectedItem.ToString());
int active = Convert.ToInt32(ddlActive.SelectedValue);
int isGVO = Convert.ToInt32(ddlIsGVO.SelectedValue);
int gvoTeamID = Convert.ToInt32(ddlGVOTeams.SelectedValue);
int profileID = Convert.ToInt32(ddlProfiles.SelectedValue);
int isSOW = Convert.ToInt16(ddlIsSOW.SelectedValue);
int headcount = Convert.ToInt32(ddlHeadcount.SelectedValue);
string updater_domain = p.Identity.Name.ToString();
string updater = "";
int index = updater_domain.IndexOf("\\");
int email_at_index = email.IndexOf("#");
if (index != -1)
{
updater = updater_domain.Substring(index + 1, 7);
}
else
{
updater = updater_domain;
}
if (firstName.Length < 2)
{
update_error = "First Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (lastName.Length < 2)
{
update_error = update_error + "Last Name should have at least 2 characters. ";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else if (email_at_index == -1 && email.Length < 5)
{
update_error = update_error + "Invalid email address.";
lblStatus.Text = update_error;
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Visible = true;
}
else
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(13);
dbManager.AddParameters(0, "#SOEID", SOEID);
dbManager.AddParameters(1, "#firstName", firstName);
dbManager.AddParameters(2, "#LastName", lastName);
dbManager.AddParameters(3, "#Email", email);
dbManager.AddParameters(4, "#REMSCode", remsCode);
dbManager.AddParameters(5, "#Active", active);
dbManager.AddParameters(6, "#IsGVO", isGVO);
dbManager.AddParameters(7, "#gvoTeamID", gvoTeamID);
dbManager.AddParameters(8, "#profileID", profileID);
dbManager.AddParameters(9, "#isSOW", isSOW);
dbManager.AddParameters(10, "#headcount", headcount);
dbManager.AddParameters(11, "#lastUpdatedBy", updater);
dbManager.AddParameters(12, "#status", active);
dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "sp_update_user");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
lblStatus.Visible = true;
lblStatus.Text = "User data updated successfully.";
lblStatus.ForeColor = System.Drawing.Color.Green;
FillFields();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
FillFields();
gvREMSDetails.Visible = false;
}
private void FillFields()
{
string soeid = Convert.ToString(Request["soeid"]);
DataSet dsUserDetails = new DataSet();
DataTable dtUserDetails = new DataTable();
DataSet dsDDLs = new DataSet();
dsUserDetails = GetUserDetails(soeid);
dtUserDetails = dsUserDetails.Tables[0];
string gvoTeam = dtUserDetails.Rows[0].ItemArray[8].ToString();
string profile = dtUserDetails.Rows[0].ItemArray[10].ToString();
string remsCode = dtUserDetails.Rows[0].ItemArray[4].ToString();
txtSOEID.Text = dtUserDetails.Rows[0].ItemArray[0].ToString();
txtFirstName.Text = dtUserDetails.Rows[0].ItemArray[1].ToString();
txtLastName.Text = dtUserDetails.Rows[0].ItemArray[2].ToString();
txtEmail.Text = dtUserDetails.Rows[0].ItemArray[3].ToString();
ddlREMS.SelectedValue = remsCode.ToString();
txtAddress.Text = dtUserDetails.Rows[0].ItemArray[5].ToString();
//Response.Write((Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString());
ddlActive.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[6])).ToString();
ddlIsGVO.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[7])).ToString();
ddlGVOTeams.SelectedValue = gvoTeam;
ddlProfiles.SelectedValue = profile;
ddlIsSOW.SelectedValue = (Convert.ToInt16(dtUserDetails.Rows[0].ItemArray[12])).ToString();
lblLastUpdatedBy_value.Text = dtUserDetails.Rows[0].ItemArray[14].ToString();
lblLastUpdatedDate_value.Text = dtUserDetails.Rows[0].ItemArray[15].ToString();
}
protected void btnGetREMSdetails_Click(object sender, EventArgs e)
{
//int remsCode = Convert.ToInt32(ddlREMS.SelectedValue);
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#remscode", Convert.ToInt32(ddlREMS.SelectedValue));
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwREMSDetails where [rems code] = #remscode");
gvREMSDetails.DataSource = ds;
gvREMSDetails.DataBind();
gvREMSDetails.Visible = true;
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
private static DataSet GetUserDetails(string soeid)
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
dbManager.CreateParameters(1);
dbManager.AddParameters(0, "#soeid", soeid);
ds = dbManager.ExecuteDataSet(CommandType.Text, "select * from vwUsersDetails where soeid = #soeid");
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
return ds;
}
private void GetDDLsItems()
{
// create ConnectDatabase object to get acces to its methods
ConnectDatabase connectDB = new ConnectDatabase();
IDBManager dbManager = connectDB.ConnectDB();
DataSet ds = new DataSet();
try
{
dbManager.Open();
ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "sp_select_edit_user_ddls");
ddlREMS.DataSource = ds.Tables[0];
ddlREMS.DataTextField = "remsCode";
ddlREMS.DataValueField = "remsCode";
ddlREMS.DataBind();
ddlActive.DataSource = ds.Tables[1];
ddlActive.DataTextField = "Active";
ddlActive.DataValueField = "ActiveID";
ddlActive.DataBind();
ddlIsGVO.DataSource = ds.Tables[2];
ddlIsGVO.DataTextField = "IsGVO";
ddlIsGVO.DataValueField = "IsGVOID";
ddlIsGVO.DataBind();
//methods.GetGVOFunctions(ddlGVOFunctions);
//int? gvoFunctionID = string.IsNullOrEmpty(ddlGVOFunctions.SelectedValue) ? (int?)null : (int?)Convert.ToInt32(ddlGVOFunctions.SelectedValue);
methods.GetGVOTeams(null, ddlGVOTeams);
ddlProfiles.DataSource = ds.Tables[3];
ddlProfiles.DataTextField = "profilename";
ddlProfiles.DataValueField = "profileID";
ddlProfiles.DataBind();
ddlIsSOW.DataSource = ds.Tables[4];
ddlIsSOW.DataTextField = "IsSOW";
ddlIsSOW.DataValueField = "IsSOWID";
ddlIsSOW.DataBind();
ddlHeadcount.DataSource = ds.Tables[5];
ddlHeadcount.DataTextField = "Headcount";
ddlHeadcount.DataValueField = "HeadcountID";
ddlHeadcount.DataBind();
}
catch (Exception error)
{
HttpContext.Current.Response.Write(error.ToString());
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
}
}
I'm not 100% I completly understand the issue, but it sounds to me that you need to have
if(!IsPostBack)
{
// load dropdown data here
}
where you load all your data into the dropdowns, and then on the dropdown have
<asp:DropDownList SelectedIndexChanged="ddlDropdown_SelectedIndexChanged" id="ddlDropdown" AutoPostBack="true"></asp:DropDownList>
Then in your code behind have
protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
}
I want to delete from the treeview the nodes,and of course the roleid and userid.and on the other hand i also want to delete from listboxes rows,but i can delete them,but after restart application they are here again.it doesnt save
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FirebirdSql.Data.FirebirdClient;
using System.Collections;
using System.Reflection;
namespace SiteYoenetim
{
public partial class ManageRoles : Form
{
private FbCommand cmd = null;
public ManageRoles()
{
InitializeComponent();
FillUsersInRollsTree();
}
private void homeToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void AddNewRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.Add(newRolesRow);
try
{
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
catch (Exception ex)
{
this.DataSet1.ROLES.Rows.Remove(newRolesRow);
MessageBox.Show("Unable to add role " + newName + ex.Message,
"Unable to add role!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
RolesListBox.SelectedIndex = -1;
}
private void DeleteRole_Click(object sender, EventArgs e)
{
string newName = string.Empty;
newName = NewRoleName.Text;
NewRoleName.Text = string.Empty; // clear the control
DataSet1.ROLESRow newRolesRow;
newRolesRow = DataSet1.ROLES.NewROLESRow();
newRolesRow.ROLENAME = newName;
this.DataSet1.ROLES.Rows.RemoveAt(RolesListBox.SelectedIndex);
this.rolesTableAdapter.Update(this.DataSet1.ROLES);
}
private void AddNewAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow newUsersRow;
newUsersRow = DataSet1.USERS.NewUSERSRow();
newUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.Add(newUsersRow);
this.usersTableAdapter.Update(this.DataSet1.USERS);
AppUsersListBox.SelectedIndex = -1;
}
HERE IT DELETES FROM APPUSER but it is again here after restart application
private void DeleteAppUser_Click(object sender, EventArgs e)
{
DataSet1.USERSRow delUsersRow;
delUsersRow = DataSet1.USERS.NewUSERSRow();
delUsersRow.NAME = NewUserName.Text;
NewUserName.Text = string.Empty;
this.DataSet1.USERS.Rows.RemoveAt(AppUsersListBox.SelectedIndex);
this.usersTableAdapter.Update(this.DataSet1.USERS);
}
private void AddUsersToRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("INSERT INTO usersToRoles (FKUserID, FKRoleID) values
(#USERID, #RoleID)", conn);
param = cmd.Parameters.Add("#USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("#RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
private void DisplayError(int userID, int roleID, string message)
{
MessageBox.Show("Unable to add user (" + userID + ") to role (" + roleID + ")" + message,
"Unable to add user to role",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
private void FillUsersInRollsTree()
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
string queryString = "select u.Name, r.RoleName from userstoRoles utr " +
" join users u on u.userID = utr.FKUserID " +
" join Roles r on r.roleID = utr.FKRoleID ";
if (rbName.Checked)
{
queryString += "order by Name";
}
else
{
queryString += "order by RoleName";
}
UsersInRoles.BeginUpdate();
UsersInRoles.Nodes.Clear();
TreeNode parentNode = null;
TreeNode subNode = null;
DataSet ds = new DataSet();
FbDataAdapter dataAdapter = new FbDataAdapter(queryString, conn);
dataAdapter.Fill(ds, "usersInRoles");
DataTable dt = ds.Tables[0];
string currentName = string.Empty;
foreach (DataRow row in dt.Rows)
{
if (rbName.Checked)
{
subNode = new TreeNode(row["roleName"].ToString());
if (currentName != row["Name"].ToString())
{
parentNode = new TreeNode(row["Name"].ToString());
currentName = row["Name"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
else
{
subNode = new TreeNode(row["Name"].ToString());
if (currentName != row["RoleName"].ToString())
{
parentNode = new TreeNode(row["RoleName"].ToString());
currentName = row["RoleName"].ToString();
UsersInRoles.Nodes.Add(parentNode);
}
}
if (parentNode != null)
{
parentNode.Nodes.Add(subNode);
}
}
UsersInRoles.EndUpdate();
}
private void RadioButtonClick(object sender, EventArgs e)
{
FillUsersInRollsTree();
}
private void ManageRoles_Load(object sender, EventArgs e)
{
this.uSERSTOROLESTableAdapter.Fill(this.dataSet11.USERSTOROLES);
this.uSERSTOROLESTableAdapter.Fill(this.DataSet1.USERSTOROLES);
this.usersTableAdapter.Fill(this.DataSet1.USERS);
this.rolesTableAdapter.Fill(this.DataSet1.ROLES);
}
private void Save_Click(object sender, EventArgs e)
{
this.Validate();
this.usersBindingSource.EndEdit();
this.usersTableAdapter.Update(this.DataSet1);
}
HERE IT SHOULD DELETE FROM TREEVIEW, but it doesnt
private void RemoveUsersFromRole_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["xxx.Properties.Settings.xxx"].ToString();
FbConnection conn = new FbConnection(connString);
conn.Open();
FbParameter param;
foreach (DataRowView userRow in AppUsersListBox.SelectedItems)
{
foreach (DataRowView roleRow in RolesListBox.SelectedItems)
{
{
int userID = Convert.ToInt32(userRow["UserID"]);
int roleID = Convert.ToInt32(roleRow["RoleID"]);
try
{
cmd = new FbCommand("DELETE FROM usersToRoles (FKUserID, FKRoleID) values (USERID, RoleID)", conn);
param = cmd.Parameters.Add("USERID", FbDbType.Integer);
param.Value = userID;
param.Direction = ParameterDirection.Input;
param = cmd.Parameters.Add("RoleID", FbDbType.Integer);
param.Value = roleID;
param.Direction = ParameterDirection.Input;
int rowsInserted = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
conn.Close();
FillUsersInRollsTree();
}
}
}
}
If your data is stored in a database, then deleting the data from the treeview and listboxes alone is not sufficient. You will have to delete the information in the database as well.
EDIT:
Your DELETE SQL command is wrong. Try to change it to:
DELETE FROM usersToRoles WHERE FKUserID = #USERID AND FKRoleID = #RoleID
(I was a mix between INSERT statement and DELETE statement.)