I'm currently trying to find a textbox control in InsertItemTemplate to test against values already in one of my database tables but I can't seem to get the FindControl to work. Below is the code I'm currently looking at:
protected void InsertButton_Click(object sender, EventArgs e)
{
TextBox linkinsTextBox = Page.FindControl("linkinsTextBox") as TextBox;
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
bool exists = false;
//The number of entries in links is counted
String linkCountQuery = " SELECT COUNT(link) from[links] where link = " + linkinsTextBox.Text + "";
SqlCommand linkCountQueryCommand = new SqlCommand(linkCountQuery, myConnection);
Int32 linkCountQueryCommandValue = (Int32)linkCountQueryCommand.ExecuteScalar();
myConnection.Close();
if (linkCountQueryCommandValue >= 1)
{
exists = true;
URLexists.Text = "URL already exists. Please enter a different URL.";
}
}
Related
So I have this DataGridView on which there are two columns which I am retrieving from my SQL Server database. Now, in the second column, we have a bit field which shows as a CheckBox in my Windows Application designer. So, I want to, on CellContentClick event be able to update the value that just got deselected into my database. But seems like I am going nowhere.
Here is my code below:
private void gvTurnOffNotifications_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
bool result = Convert.ToBoolean(row.Cells[1].Value);
if (result == true)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
int temp = 1;
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where AllowNotification='" + false+ "'";
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
And then when I click on my "Update" button, I want to send the updated griddata for storing in my database as below:
private void btnUpdateTurnOff_Click(object sender, EventArgs e)
{
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLDataAdapter = new SqlDataAdapter("spGetAllUpdatedNotifications", mySQLConnection);
mySQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
DataSet ds = new DataSet();
mySQLDataAdapter.Fill(ds);
mySQLDataAdapter.UpdateCommand = mySQLCommand;
mySQLDataAdapter.Update(ds);
}
}
The spGetAllUpdatedNotifications object in my Update block is a stored procedure I am calling just to retrieve the records from the database so I can update them on the fly in my DataSet. Here is the definition below:
create proc spGetAllUpdatedNotifications
as
begin
SELECT UserName, AllowNotification FROM UsersNotified where AllowNotification=1
end
GO
For more context: When my form loads, I am selecting all the records from the database which have their AllowNotification field set to bit 1 (true in C#) and once a user unticks a specific user (in other words, that user would not be allowed to receive notifications anymore) and once I click on the Update button, it should set the property to false (bit 0 in the database).
Instead of updating the one record which I have deselected, it updates all of them. "All" in this case are the records which have AllowNotification=1. I only want to set AllowNotification=0 for the deselected/unchecked record only
Any suggestions on how I can go about achieving this?
I am not sure what logic makes you to loop thru all the rows of the DataGridView just to update one row in the database.
If you want to update AllowNotification value for the username for which checkbox is checked or unchecked the logic would be this.
Figure out the updated value of the checkbox which is clicked in the gridview.
Store the updated value (True or False) in a boolean variable.
Retrieve the corresponding username of from the other cell of the same row the gridview.
Execute update query with criteria "WHERE UserName = {userName}".
You need to write CellContentClick event of the DataGridView as following.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1) //Assuming Checkbox is displayed in 2nd column.
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
var result = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
var userName = this.dataGridView1[0, e.RowIndex].Value; //Assumin username is displayed in fist column
var connectionString = "Your Connection String";
//Set value of your own connection string above.
var sqlQuery = "UPDATE UsersNotified SET AllowNotification = #allowNotification WHERE UserName = #userName";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sqlQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#allowNotification", SqlDbType.Bit).Value = result;
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = userName;
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
This should help you resolve your issue.
I have a partial solution (It doesn't work a 100% but at least its a step in the right direction):
private void gvTurnOffNotifications_SelectionChanged(object sender, EventArgs e)
{
if (gvTurnOffNotifications.SelectedCells.Count > 0)
{
int selectedrowindex = gvTurnOffNotifications.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = gvTurnOffNotifications.Rows[selectedrowindex];
getUserSelected = Convert.ToString(selectedRow.Cells["UserName"].Value);
MessageBox.Show(getUserSelected);
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where UserName='" + getUserSelected + "'";
//MessageBox.Show(cell.Value.ToString());
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
Problem is that it just takes the first row without me having selected the row I want to deselect.
Im writing stock program - just to learn a little bit of c# and i got some problem.
Here is a part of mine code
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
string conString =
"Data Source=192.168.0.195;" +
"Initial Catalog=test;" +
"User id=sa;" +
"Password=12345678;";
string query = "Select * from dokumenty where symbol='" + comboBox_symbol.Text + "' ; ";
SqlConnection conDB = new SqlConnection(conString);
SqlCommand cmdDB = new SqlCommand(query, conDB);
SqlDataReader sqlReader;
try
{
conDB.Open();
sqlReader = cmdDB.ExecuteReader();
while (sqlReader.Read())
{
var s_Typ_dok = sqlReader.GetString(1);
var s_Symbol = sqlReader.GetString(2);
var s_Delivery_date = sqlReader.GetString(3);
var s_Invoice_date = sqlReader.GetString(4);
var s_Invoice_nr = sqlReader.GetInt32(5).ToString();
var s_Sybtype = sqlReader.GetString(6);
var s_Produkt_index = sqlReader.GetString(7);
var s_Produkt_name = sqlReader.GetString(8);
var s_Quantity = sqlReader.GetInt32(9).ToString();
var s_Price = sqlReader.GetString(10);
var s_From_warehouse = sqlReader.GetString(12);
var s_To_warehouse = sqlReader.GetString(13);
var s_Currency = sqlReader.GetString(14);
var s_Supplier_reciever = sqlReader.GetString(15);
comboBox_Type.Text = s_Typ_dok;
textBox_symbol.Text = s_Symbol;
textBox_deliveryDate.Text = s_Delivery_date;
textBox_invoiceDate.Text = s_Invoice_date;
textBox_invoice.Text = s_Invoice_nr;
textBox_subtype.Text = s_Sybtype;
textBox_produkt_index.Text = s_Produkt_index;
textBox_name.Text = s_Produkt_name;
textBox_quantity.Text = s_Quantity;
textBox_price.Text = s_Price;
comboBox_from_warehouse.Text = s_From_warehouse;
comboBox_to_warehouse.Text = s_To_warehouse;
comboBox_currency.Text = s_Currency;
textBox_supplier.Text = s_Supplier_reciever;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
which works ok, when i selected something in combobox5 it auto insert things to Textboxes when it exist in DB, but when i erase this thing which i select in combobox5, text in textboxes is still there. Is there any chance to erase it when combobox5 == null?
On SelectedIndexChanged event add one condition to check SelectedIndex==0, if selected index is zero then clear text of Text box,
If you don't wants to edit text from combo box then you can set combobox as non editable by setting
comboBox5.DropDownStyle = ComboBoxStyle.DropDownList;
This will not allow user to edit text from combobox
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox5.SelectedIndex==0)
{
TextBoxId.Text=String.Empty;
}
else
{
//Rest of your code here
}
}
I am trying to populate textboxes (txtFirstName, txtSecondName) programatically by allowing the users to type in (say, 4) in a textbox and press the button to populate these into a panel. So if they put 2 in then they will get 2 rows of textboxes for first and last name.
My problem is when I save I cannot get the text from these textboxes that were created on the fly. Any suggestions?
//button
protected void Button1_Click(object sender, EventArgs e)
{
int number = int.Parse(TextBox1.Text);
for (int i = 0; i < number; i++)
{
//Horizontal line
LiteralControl hrline = new LiteralControl();
hrline.Text = "<hr />";
//Textboxes
TextBox txtFirstName = new TextBox();
TextBox txtSecondName = new TextBox();
//FirstName
txtFirstName.ID = "txtFirstName" + i;
txtFirstName.Text = "First Name " + i;
//Second name
txtSecondName.ID = "txtSecondName" + i;
txtSecondName.Text = "Last Name " + i;
buttonPanel.Controls.Add(hrline);
pnlteacherExp.Controls.Add(txtFirstName);
pnlteacherExp.Controls.Add(txtSecondName);
pnlteacherExp.Controls.Add(hrline);
}
}
Save button to save to database:
protected void btnSave_Click(object sender, EventArgs e)
{
int number = int.Parse(TextBox1.Text);
for (int i = 0; i < number; i++)
{
string connectionString = WebConfigurationManager.ConnectionStrings["crud_connection"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Store_proc";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Parameters.AddWithValue("#staffPayroll", "payroll_num");
cmd.Parameters.AddWithValue("#FirstName", ??);
cmd.Parameters.AddWithValue("#Surname", ??);
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
You can get the post parametres using the Request.Form.
The posted parametres are use the name value of the rendered html element, or the UniqueID on server side, but because you can not set the UniqueID on server side, and because you make them dynamically, probably the name is rendered the same as the id, at least on my tests, and the line will be as:
cmd.Parameters.AddWithValue("#FirstName",
Request.Form["txtFirstName" + i.ToString()]);
To clarify, normally you need to do this Request.Form[control.UniqueID] to get the posted value, but because you do not have the control because you make it dynamically and is not there any more, the next is to get the post value with the posted name, so the posted name is this one "txtFirstName" + i.ToString() the way you makes them.
relative:
asp.net request.form
Accessing control client name and not ID in ASP.NET
Get info about Http Post field order
You can try the following:
TextBox txtFirstName = Controls.FindControl(string.Format("txtFirstName{0}", i)) as TextBox;
string name = txtFirstName.Text;
You can browse through this link to see how you can retain state of the dynamically created control: http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
I want to update this form's Login and Logout Time:
My code is :
protected void btnUpdate_Click(object sender, EventArgs e)
{
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
long DayLogId = Convert.ToInt64(Request.QueryString["ID"]);
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =#"Data Source=DELL\SQLSERVER1;Initial Catalog=LoginSystem;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [DayLog] SET [LoginTime]=#LoginTime,[LogOutTime]=#LogOutTime WHERE [DayLogId]=#DayLogId");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#LoginTime", LoginTime);
dataCommand.Parameters.AddWithValue("#LogOutTime", LogOutTime);
dataCommand.Parameters.AddWithValue("#DayLogId", DayLogId);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
At the first two lines of method ,
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
when I debug , it does not show the value that I reinserted. This code works if I mannually write
string LoginTime = "11:44:11";
string LogOutTime = "12:44:11";
NOTE:
The value of forms in text box is coming from another page GridView.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
GridViewRow grRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
Label DayLogId = grRow.FindControl("lblDayLogId") as Label;
if (Convert.ToInt16(DayLogId.Text) > 0)
{
Response.Redirect("~/Employee/OutLog_Day.aspx?ID=" + DayLogId.Text, false);
}
}
}
You should make sure that the text box gets populated before the click event runs. As Steve suggested, usually you get this when you initialize the data on every postback which is unnecessary if the data is not changed.
edit: Solved
I have a label that gets populated with a value from a database. If the user enters this value into a textbox below, I want to change the background. The label displays the value fine on screen, but when I try to match the values in the textbox's textchanged event, it shows as null.
public void button1_Click(object sender, RoutedEventArgs e)
{
txtAnswer.Clear();
txtAnswer.Background = Brushes.White;
int number = r.Next(3) + 1;
string queryEnglish = "SELECT englishVerb FROM verbTable WHERE (verbID = " + number + ")";
string queryFrench = "SELECT frenchVerb FROM verbTable WHERE (verbID = " + number + ")";
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\verbs.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand command = new SqlCommand(queryEnglish, con))
{
this.lblEnglishVerb.Content = (string)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryFrench, con))
{
this.lblFrenchVerb.Content = (string)command.ExecuteScalar();
}
}
}
public void txtAnswer_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtAnswer.Text == lblFrenchVerb.Content.ToString())
txtAnswer.Background = Brushes.LightGreen;
if (txtAnswer.Text == "test")
txtAnswer.Background = Brushes.AliceBlue;
}
Textchanged will probably get triggered the moment 'nothing' is placed into the Content. So on the first txtAnswer_TextChanged you might get nothing.