I tried:
System.Web.UI.Page FormPage;
object FormControl = FormPage.FindControl("lblUserNames");
object literalControl = FormPage.FindControl("litMessages");
But it is throwing an error: "Use of unassigned local variable 'FormPage'"
So how do I set the textbox/label value in a static method?
The whole source:
[WebMethod]
public static void DeleteItem()
{
HttpCookie reader = HttpContext.Current.Request.Cookies["roomId"];
string query = "[Get_Messages]";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#roomId", reader.Value);
GetData(cmd);
}
Get data from database to dataset and bind it to div.
private static DataSet GetData(SqlCommand cmd)
{
int cntr = 0;
HttpCookie cookieUserName = HttpContext.Current.Request.Cookies["userName"];
string username = cookieUserName.Value;
System.Web.UI.Page FormPages;
object FormsControl = FormPages.FindControl("lblUserNames");
string strConnString = ConfigurationManager.ConnectionStrings["LinqChatConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Messages");
return ds;
if (ds.Tables[0].Rows.Count != 0)
{
StringBuilder sb = new StringBuilder();
int i = (ds.Tables[0].Rows.Count - 1);
for (int j = 0; j <= i; j++)
{
string personName = ds.Tables[0].Rows[j]["Username"] == null ? "" : ds.Tables[0].Rows[j]["Username"].ToString();
string gender = ds.Tables[0].Rows[j]["Sex"] == null ? "" : ds.Tables[0].Rows[j]["Sex"].ToString();
string message = ds.Tables[0].Rows[j]["Text"] == null ? "" : ds.Tables[0].Rows[j]["Text"].ToString();
if (cntr == 0)
{
if (username == personName)
{
sb.Append("<div style='padding: 10px;text-align:right'>");
}
else
{
sb.Append("<div style='padding: 10px;'>");
}
cntr = 1;
}
else
{
if (username == personName)
{
sb.Append("<div style='background-color: #EFEFEF;padding: 10px;text-align:right'>");
}
else
{
sb.Append("<div style='background-color: #EFEFEF;padding: 10px;'>");
}
cntr = 0;
}
((System.Web.UI.WebControls.Label)FormControl).Text = "<span style='color: Blue;'><b line-height:22px>" + personName + "</b></span>";
string lblUserNames = ((System.Web.UI.WebControls.Label)FormControl).Text;
//lblUserNames.Text
((System.Web.UI.WebControls.Label)FormControl).Visible = true;
//lblUserNames.Visible = true;
if (gender.ToLower() == "m")
{
if (username == personName)
{
sb.Append(message + "</div>");
}
else
{
sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle;' alt=''> " + lblUserNames + " " + message + "</div>");
}
}
else
{
if (username == personName)
{
sb.Append(message + "</div>");
}
else
{
sb.Append("<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''> " + lblUserNames + " " + message + "</div>");
}
}
}
((System.Web.UI.WebControls.Literal)FormsControl).Text = sb.ToString();
((System.Web.UI.WebControls.Label)FormControl).Visible = false;
}
else
{
((System.Web.UI.WebControls.Label)FormControl).Visible = false;
}
}
}
}
}
You could try to set it?
FormPage page = new FormPage();
object FormControl = page.FindControl("lblUserNames");
object literalControl = page.FindControl("litMessages");
Related
I am not a programer, I just have a passion for this. I am doing a project which can facilitate my work, but I am facing the error described when connecting to the DB. Here is the code:
public partial class Form1 : Form
{
string dbcon = "#Data Source= KMS.db;Version=3;";
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlcon = new SQLiteConnection(dbcon);
if ((textusername.Text == "") && (textpassword.Text == "") || (textusername.Text == "") || (textpassword.Text == ""))
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Username and / or password are empty!";
}
else
{
try
{
sqlcon.Open();
string query = "SELECT * FROM user WHERE Username = '" + textusername.Text + "' AND Password = '" + textpassword.Text + "'";
SQLiteCommand com = new SQLiteCommand(query, sqlcon);
com.ExecuteNonQuery();
SQLiteDataReader dr = com.ExecuteReader();
int i = 0;
while (dr.Read())
{
i++;
}
if(i == 1)
{
KMS_MainMenu MainMenu = new KMS_MainMenu();
MainMenu.Show();
this.Hide();
}
if(i < 1)
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Invalid Username and / or Password";
textpassword.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Error while logging: " + ex);
}
}
}
after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}
I'm using SQLite with C#.
I use the following method to loop through a list of tv shows and their episodes and insert them into the database. It ends up entering about 1200 rows and takes 2 minutes 28 seconds. It feels like that's kinda slow so I would like people to look over my method and see if i'm doing something stupid (I'm sorta new to this).
public void InsertAllEpisodes(List<TVDBSharp.Models.Show> showList)
{
using (SQLiteConnection dbconnection = new SQLiteConnection(connectionString))
{
string seasonNumber;
string episodeNumber;
string insertShowSQL = #"INSERT INTO AllEpisodes (Key, ShowName, ShowId, EpisodeName, SeasonEpisode) VALUES (#Key, #ShowName, #ShowId, #EpisodeName, #SeasonEpisode)";
foreach (var show in showList)
{
foreach (var episode in show.Episodes)
{
if (episode.SeasonNumber != 0)
{
string seasonEpisode = "default";
if ((episode.SeasonNumber != 0) && (episode.SeasonNumber.ToString().Length == 1)) { seasonNumber = "0" + episode.SeasonNumber.ToString(); }
else { seasonNumber = episode.SeasonNumber.ToString(); }
if (episode.EpisodeNumber.ToString().Length == 1) { episodeNumber = "0" + episode.EpisodeNumber.ToString(); }
else { episodeNumber = episode.EpisodeNumber.ToString(); }
seasonEpisode = seasonNumber + episodeNumber;
SQLiteCommand command = new SQLiteCommand(insertShowSQL, dbconnection);
command.Parameters.AddWithValue("Key", show.Id + seasonEpisode);
command.Parameters.AddWithValue("ShowName", show.Name);
command.Parameters.AddWithValue("ShowId", show.Id);
command.Parameters.AddWithValue("EpisodeName", episode.Title);
command.Parameters.AddWithValue("SeasonEpisode", seasonEpisode);
dbconnection.Open();
try
{
command.ExecuteScalar();
}
catch (SQLiteException ex)
{
if (ex.ResultCode != SQLiteErrorCode.Constraint)
{
File.AppendAllText(programDataPath + "SQLErrors.txt", ex.Message + "\n");
}
}
dbconnection.Close();
}
}
}
}
}
I read up on and used sqlComm = new SQLiteCommand("begin", dbconnection) and sqlComm = new SQLiteCommand("end", dbconnection) and it inserted it in less than 1 second.
public void InsertAllEpisodes(List<TVDBSharp.Models.Show> showList)
{
using (SQLiteConnection dbconnection = new SQLiteConnection(connectionString))
{
dbconnection.Open();
string seasonNumber;
string episodeNumber;
string insertShowSQL = #"INSERT INTO AllEpisodes (Key, ShowName, ShowId, EpisodeName, SeasonEpisode) VALUES (#Key, #ShowName, #ShowId, #EpisodeName, #SeasonEpisode)";
SQLiteCommand sqlComm;
sqlComm = new SQLiteCommand("begin", dbconnection);
sqlComm.ExecuteNonQuery();
foreach (var show in showList)
{
foreach (var episode in show.Episodes)
{
if (episode.SeasonNumber != 0)
{
string seasonEpisode = "default";
if ((episode.SeasonNumber != 0) && (episode.SeasonNumber.ToString().Length == 1)) { seasonNumber = "0" + episode.SeasonNumber.ToString(); }
else { seasonNumber = episode.SeasonNumber.ToString(); }
if (episode.EpisodeNumber.ToString().Length == 1) { episodeNumber = "0" + episode.EpisodeNumber.ToString(); }
else { episodeNumber = episode.EpisodeNumber.ToString(); }
seasonEpisode = seasonNumber + episodeNumber;
sqlComm = new SQLiteCommand(insertShowSQL, dbconnection);
sqlComm.Parameters.AddWithValue("Key", show.Id + seasonEpisode);
sqlComm.Parameters.AddWithValue("ShowName", show.Name);
sqlComm.Parameters.AddWithValue("ShowId", show.Id);
sqlComm.Parameters.AddWithValue("EpisodeName", episode.Title);
sqlComm.Parameters.AddWithValue("SeasonEpisode", seasonEpisode);
try
{
sqlComm.ExecuteScalar();
}
catch (SQLiteException ex)
{
if (ex.ResultCode != SQLiteErrorCode.Constraint)
{
File.AppendAllText(programDataPath + "SQLErrors.txt", ex.Message + "\n");
}
}
}
}
}
sqlComm = new SQLiteCommand("end", dbconnection);
sqlComm.ExecuteNonQuery();
dbconnection.Close();
}
}
when i run the code this erorr apeared
incorrect syntax near the keyword where c#
public SqlDataReader GetDR(CommandType HandelMode, string SQLStat, List<SqlParameter> Parms)
{
SqlDataReader R = null;
SqlCommand com = new SqlCommand();
SqlConnection Con = GetConn();
try
{
com.CommandText = SQLStat;
com.Connection = Con;
com.CommandType = HandelMode;
if (Parms != null)
{
foreach (SqlParameter P in Parms)
{
com.Parameters.Add(P);
}
}
R = com.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
return null;
}
finally
{
Con.Close();
}
return R;
}
private void pictureBox10_Click_2(object sender, EventArgs e)
{
List<SqlParameter> ParsList = new List<SqlParameter>();
string SelectStatement = "Select ID,Aname,Ename,I_D from " + ScreenMasterTableName;
string Cond = " ID_Co=#ID_Co";
ParsList.Add(new SqlParameter("#ID_Co", FormInfo.ID_Co));
if (S_ID.Text != "")
{
decimal D = 0;
decimal.TryParse(S_ID.Text, out D);
Cond += " and ID=#ID";
ParsList.Add(new SqlParameter("#ID", D));
}
if (S_Aname.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Aname =#Aname";
ParsList.Add(new SqlParameter("#Aname", S_Aname.Text));
}
if (S_Ename.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Ename =#Ename";
ParsList.Add(new SqlParameter("#Ename", S_Ename.Text));
}
if (Cond != "")
Cond = " where " + Cond;
var L = Bus.GetSearchedData(SelectStatement + Cond, ParsList);
dataGridView1.DataSource = L;
label9.Text = L.Count.ToString();
}
Assuming your s_id is filled in you will have a query like this:
where and ID=#ID
Here is my current code behind for the OnRowUpdating event and SQL statement to update the database. It is throwing an exception:
System.NullReferenceException: Object reference not set to an instance of an object.error
Code:
protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtSu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox1"); // each textbox refers to the Am then Pm day
TextBox txtSu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox2");// sun pm
TextBox txtMo = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox3");// mon am
TextBox txtMo1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox4");//mon pm
TextBox txtTu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox5");
TextBox txtTu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox6");
TextBox txtWe = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox7");
TextBox txtWe1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox8");
TextBox txtTh = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox9");
TextBox txtTh1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox10");
TextBox txtFr = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox11");
TextBox txtFr1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox12");
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
TextBox txtSa1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox14");
string sql = "UPDATE tblEMPLOYEE SET EmployeeID=#ID, " +
"AvailSun=#AvSu, " +
"AvailSun1=#AvSu1, " +
"AvailMon=#AvMo, " +
"AvailMon1=#AvMo1, " +
"AvailTues=#AvTu, " +
"AvailTues1=#AvTu1, " +
"AvailWedn=#AvWe, " +
"AvailWedn1=#AvWe1, " +
"AvailThurs=#AvTh, " +
"AvailThurs1=#AvTh1, " +
"AvailFri=#AvFr, " +
"AvailFri1=#AvFr1, " +
"AvailSat=#AvSa, " +
"AvailSat1=#AvSa1 " +
"WHERE EmployeeID=#ID";
CMethods.executeNonQuery(sql, "#ID", txtID.Text, "#AvSu", txtSu.Text, "#AvSu1", txtSu1.Text, "#AvMo", txtMo.Text, "#AvMo1", txtMo1.Text, "#AvTu", txtTu.Text, "#AvTu1", txtTu1.Text, "#AvWe", txtWe.Text, "#AvWe1", txtWe1.Text, "#AvTh", txtTh.Text, "#AvTh1", txtTh1.Text, "#AvFr", txtFr.Text, "#AvFr1", txtFr1.Text, "#AvSa", txtSa.Text, "#AvSa1", txtSa1.Text, "#ID", ID);
GV.EditIndex = -1;
fillUsers();
}
private void fillUsers()
{
GV.DataSource = CMethods.returnTable("SELECT * FROM tblEMPLOYEE WHERE EmployeeID=" + lblEmployee.Text);
GV.DataBind();
}
In Cmethods
public static class CMethods
{
public static DataTable returnTable(String CommandText, params Object[] values)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "tbl");
return ds.Tables["tbl"];
}
public static bool executeNonQuery(String CommandText, params Object[] values)
{
bool bln = true;
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
bln = false;
}
finally
{
con.Close();
}
return bln;
}
public static double returnValue(string str)
{
double dblTemp = 0.0D;
string strTemp = String.Empty;
bool blnFirstDec = false;
bool blnFirstNeg = false;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "-")
{
blnFirstNeg = true;
}
if (IsNumeric(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
{
if (str.Substring(i, 1) == ".")
{
if (!blnFirstDec)
{
blnFirstDec = true;
strTemp += ".";
}
}
else
{
strTemp += str.Substring(i, 1);
}
}
}
FindControl control may not return control if you not provide correct control id
for example you have given txtBo13(missing x) but actually you may have txtBox13,
so below code return null for txtSa
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBo13");
when you call Text property of txtSa you will get NullReferenceException
if you have given id as txtBox13, change the code accordingly
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
And also you may have forgot to set #student parameter value