Form get blank when Page_Load function is called? - c#

I am facing a problem in my form. There are two text field and then there is drop-down menu, which link to a database.
When I click on the drop down menu, my two text fields are getting empty.
protected void OnChange_Acdemics(object Sender, EventArgs e)
{
DropDownList list = (DropDownList)Sender;
string value = (string)list.SelectedValue;
// degrees_dropdown.Visible = true;
try
{
// String query = "SELECT Degree_types.detail,Degree_Detail.GPA FROM Degree_Detail INNER JOIN Degree_types ON Degree_Detail.Degree_tilte = Degree_types.Degree_title where Degree_types.degree_type = '" + value + "';";
String query = "Select detail from Degree_Detail where id=" + int.Parse(value) + ";";
Dt = dbComm.GetDataTable(query);
Degree_Selection.DataTextField = "detail";
// Degree_Selection.DataValueField = "GPA";
Degree_Selection.DataSource = Dt;
Degree_Selection.DataBind();
}
catch (Exception ex)
{
}
}

You need to take care of this by using Page.IsPostBack:
if(!Page.IsPostBack)
{
// load page
}
else
{
// check input values and set it again
}

Related

c# (vbs-15) how to fill datagrid and provide links

Sorry guys, but am new to c# and vbs. what am trying to do is to fill datagrid or any equivalent then i need to provide click-able buttons/links to each row.
When user click the button, the app should pass the row-id clicked to new (another) form.
...
p.textquery = "SELECT * FROM members ORDER BY member_id DESC LIMIT 250";
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=" + p.dbname() + ";Version=3;");
m_dbConnection.Open();
try
{
SQLiteCommand command = new SQLiteCommand(p.textquery, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
bool rows = reader.HasRows;
if (rows)
{
while (reader.Read())
{
patient_id = reader["patient_id"].ToString();
// Here i need to show results to user but the user should have a button to select the row
}
return;
}
else
{
p.alert("You do not have members in the system");
return;
}
}
catch
{
p.alert("SQL has error - (database error)");
return;
}
...
The problem is how to provide datagrid or any equivalent which has button where user can click to view the record.
Your help is highly appreciated
EDIT
private void dataGridView1_CellContentClick_2(object sender, DataGridViewCellEventArgs e)
{
plugin p = new plugin();
try {
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewButtonCell)
{
//I need the value of the column here member_id is only showing the rowindex and columnindex now i need the value
p.alert(dataGridView1.Rows[e.ColumnIndex].Cells[e.ColumnIndex].ToString());
}
else
{
p.alert(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString() + " on else");
}
}
catch (Exception v)
{
//p.alert("Header clicked ");
}
}
EDIT - ANSWER
dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
where Cells[2] is the targeted cell
Drag and drop a datagridview from the toolbox to the window, Add All the columns in your data table to it using properties--> columns in that add a button column or a link column.
Bind data to grid as below
DataTable dtMembers = new DataTable();
p.textquery = "SELECT * FROM members ORDER BY member_id DESC LIMIT 250";
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=" + p.dbname() + ";Version=3;");
try
{
SQLiteDataAdapter da = new SQLiteDataAdapter(p.textquery,m_dbConnection);
m_dbConnection.Open();
da.Fill(dtMembers);
m_dbConnection.Close();
if(dtMembers.Rows.Count > 0)
dgvMembers.DataSource = dtMembers;
else
p.alert("You do not have members in the system");
}
catch
{
p.alert("SQL has error - (database error)");
return;
}
Implement DataGridView cell content click
private void dgvMembers_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(dgvMembers.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewButtonCell)
{
//Write your code here
}
}
See below I have text property where I wrote click here, that's where you need to put button name

C# Passing Values between dependent Comboboxes

I'm relatively new but I've been researching this issue for over 2 days, so I think I've done my due diligence ... however if this has already been answered before I apologize.
My basic issue is I'm trying to create some dependent combo boxes. The wrinkle is the displayed value is typically not the lookup value for the next query/Combo box (I'm using an OLEDB compliant data base)
For example: Table1 (T1) contains ID (int) & NM (string), Table2 (T2) contains ID (int) & STATUS (string). I run Query1 (Q1) to display T1.NM in Combobox1 (CB1), when selected I run Query1a to lookup/get the selected Table1.ID to pass to Query2 that populates Combobox2. The connection string and Q1 work fine, CB1 displays properly, but once I select this error is thrown:
"OleDbException .. SQL Passthru expression ... using equals (=) has components that are of different data types"
// ** Initial connection & populate CB1 - This works fine **
public void comboboxLoad()
{
string conn3str = <Connection String >;
string query1 = "select NM from Table1 where REFVALUE=1 ; ";
OleDbConnection conn3 = new OleDbConnection(conn3str);
OleDbCommand tblRow1 = new OleDbCommand(query1, conn3);
OleDbDataReader rdRow1;
try
{
conn3.Open();
lblConnState.Text = "Connection Successful";
rdRow1 = tblRow1.ExecuteReader();
while (rdRow1.Read())
{
int colindx1 = rdRow1.GetOrdinal("NM");
string sItbl = rdRow1.GetString(colindx1);
CB1.Items.Add(sItbl);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
// ** Get value from CB1, create query to populate CB2 **
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
conn3.Open();
// Pass the selected value from CB1 (string) equal to Table1.NM (string)
string query1a = "select ID from Table1 where NM = '" + CB1.Text + "' ; ";
OleDbCommand TabID = new OleDbCommand(query1a, conn3);
int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());
// Pass the variable TabId2 (int) equal to Table2.ID (int)
string query2 = "select STATUS from Table2 where ID = '" + TabId2 + "'; ";
OleDbCommand tblRow2 = new OleDbCommand(query2, conn3);
// OleDbDataReader rdTabID;
// OleDbDataReader rdRow2;
try
{
OleDbDataReader rdRow2 = TabID.ExecuteReader();
OleDbDataReader rdTabID = tblRow2.ExecuteReader(); // ** Error points to this line **
while (rdRow2.Read())
{
int TabIdidx = rdTabID.GetOrdinal("ID");
string TabIDVal = rdTabID.GetString(TabIdidx);
// Pass reference ID to label on form
lblBTableID.Text = TabId2.ToString();
int colindx1 = rdRow2.GetOrdinal("STATUS");
string sIntVal = rdRow2.GetString(colindx1);
cmbLowLvl.Items.Add(sIntVal);
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
Are you positive you're getting a value back on this line int TabId2 = Convert.ToInt32(TabID.ExecuteScalar());?
Convert.ToInt32 doesn't throw a ArgumentNullException like int.Parse does so it's possible that the variable is not getting set.
Also you may want to consider changing your queries to use parameterized SQL rather than concatenation for security purposes.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
I've been able to figure out the problem. I'm really not sure why it didn't work originally, but I think it was a reader mismatch, since I was only looking for a single value back from the query ExecuteScalar() seemed to do the trick and I didn't need the 'while' loop. The working code is below.
Next I'll need to pass this return value (ID) in my next query to populate CB2. Thanks #
private void CB1_SelectedIndexChanged(object sender, EventArgs e)
{
string conn3str = <Connection String >;
OleDbConnection conn3 = new OleDbConnection(conn3str);
// Pass the selected value from CB1 (string) equal to Table1.NM (string) but return the int ID.
OleDbCommand tblRow2 = new OleDbCommand("select ID from Table1 where NM= '"+ CB1.Text +"' ;" , conn3);
try
{
conn3.Open();
string r2 = Convert.ToString(tblRow2.ExecuteScalar());
MessageBox.Show(r2);
lblBTableID.Text = "ID Code= " + r2;
conn3.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}

Table not updated in database after changing values from Textbox linked to Selected Item from ListView

This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.

i want to search the database of what the user entered and display all the possible occurrence of the word

public string[] ResultsQuery;
public int i;
public string criteria;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connString = #"Data Source=ITLAPTOP\SQLEXPRESS;Initial Catalog=trial;Integrated Security=True";
SqlConnection connStudent = new SqlConnection(connString);
connStudent.Open();
if (Request.QueryString[TextBox1.Text] != null)
{
ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');
foreach (string textbox1 in ResultsQuery)
{
if (!string.IsNullOrEmpty(criteria))
criteria += " OR ";
criteria += "SearchName LIKE '%" + textbox1 + "%' ";
}
string SqlInsertStatement = #"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
SqlCommand cmdTxt = new SqlCommand(SqlInsertStatement, connStudent);
SqlDataReader dtrACode = cmdTxt.ExecuteReader();
dtrACode.Read();
try
{
if ((dtrACode["SearchName"].ToString().Trim().Length != 0))
{
}
ListBox1.Items.Add(dtrACode["SearchName"].ToString());
}
catch (Exception)
{
ListBox1.Items.Add("NO RECORD FOUND!");
}
connStudent.Close();
connStudent.Dispose();
}
}
i want to display all occurrence of the keyword the user input, for example
list in database:
abCARdfg
CARsdg
CAR
dfgsd
sdkgs
== when i search the word CAR all the string with CAR should be displayed and dfgsd,sdkgs will not be displayed
the query is working just like what i was expecting the SQL server to display but i dont know where to place it in the code in c#, and when i click the button it does not display anything even the NO RECORD FOUND which serves as a error handler
Since I dont have access to your code, my best guess is that you have an error with the following line:
string SqlInsertStatement = #"select * from trial.dbo.Student where Student.SearchName where '" + criteria;
Replace that with the following:
string SqlInsertStatement = #"select * from trial.dbo.Student where " + criteria;
Remove the try/catch and post the details of the Exception that is thrown. There is definately an error in your query. For example, you repeat a "where".
where Student.SearchName where
Also, your code has SQL injection vulnerability in that the textbox1 value can contain anything and is not escaped. For example, a person can type '; -- delete from TABLE;
and delete everything in your table...

Displaying records in Same Gridview when Search Button in particular panel is clicked

I have 2 Panels on one page(SAPInfo, OSInfo). In SAPInfo panel there are 3 textboxes(SID, Client,User_id) and 1 SEARCH button. After clicking SEARCH button i want to display data of SAP table(user_id,Descriptio,sap_system_password) in Gridview on the next page. Similarly In OSInfo panel there are 2 text boxes(IP/HostName,User_id) and 1 SEARCH button. After clicking SEARCH button i want to display data of OS table(user_id,Descriptio,os_system_password) in the same Gridview. The Gridview has 4 columns(UserID,Description,Password,Change Password) SAP table contains fields as(sid,client_no,user_id,sap_system_password,description) OS table contains fields as(user_id,ip,host_name,os_system_password,description)
How to do this? Please help..
this is my Search button(SAP) code
protected void btnSAPSearch_Click(object sender, EventArgs e)
{
try
{
using (MySqlConnection conn = new MySqlConnection(clsUser.connStr))
{
conn.Open();
string strQuery = "select DISTINCT user_id,description,sap_system_password from sap_password_info where user_id is not null";
if (txtSid.Text !="")
{
strQuery += " AND sid = '" + txtSid.Text + "'";
}
if (txtClient.Text != "")
{
strQuery += " AND client_no = '" + txtClient.Text + "'";
}
if (txtUser.Text != "")
{
strQuery += " AND user_id = '" + txtUser.Text + "'";
}
MySqlCommand cmd = new MySqlCommand(strQuery, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
Session["userinfo"] = dt;
Response.Redirect("~\\PasswordInformation_Details.aspx");
}
}
catch (Exception ex)
{
//lblMessage.Text = DataObjects.Error_Message();
lblMsg.Text = ex.Message.ToString();
}
}
The solution is pretty simple. Pass the search criteria as query string to your other page.
So on click of search button(SAP Panel) build a query string like following
//if sap
string url = "Result.aspx?Mode=SAP&sid=some_sid&client=some_client&user_id=some_user_id;
Response.Redirect(url, false);
So on click of search button(OS Panel)
//if OS
string url = "Result.aspx?Mode=OS&ip=some_ip&user_id=some_userId;
Response.Redirect(url, false);
ON result page page_load
if(Request.QueryString["Mode"] =="SAP")
{
//bring sap result dataset
}
else
{
// bring os result dataset
}
//bind it to gridView
resultGridView.DataSource = dsResult
resultGridView.DataBind();
Keep in mind. make the autogeneratedcolumn = true on the grid view. Now your grid view would display whatever result would be given to it(3 column, 4 columns).The columns would be dynamically generated now.
EDIT 1
After search, you would have some dataset with the result. To change the grid header, simply change the column name in the dataTable. What ever column you would give, would be displayed by the grid
datatable.Columns["original_column_name"].ColumnName = "new column name";
//For adding a new column, just simply do this to your result set
datatable.Columns.Add("Change Password");
EDIT 2
string strQuery = "select DISTINCT user_id as User Id,description as Description,sap_system_password as Sap System Password from sap_password_info where user_id is not null";
Also see this : Column Alias

Categories

Resources