I have a gridview object that I am using to bind to a datasource. Upon the selectedIndexChanging event of the gridview, I would like to bring the data shown in the gridview into the textboxes on the form. However, when the data contains alphanumeric characters such as &'"", the data from the grid is showing ;amp, #S etc. and all other weird characters whenever I enter an alphanumeric character. Is there a way to prevent these characters from popping up in the textboxes when taking data from the grid?
The code that I have so far:
protected void grdActions_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedRow1 = grdActions.SelectedRow.RowIndex;
hdnIndexNo.Value = grdActions.Rows[selectedRow1].Cells[1].Text;
ddlActionType.SelectedValue = grdActions.Rows[selectedRow1].Cells[3].Text;
if (grdActions.Rows[selectedRow1].Cells[4].Text == null || grdActions.Rows[selectedRow1].Cells[4].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[4].Text == " ")
{
txtDetails.Text = string.Empty;
}
else
{
txtDetails.Text = grdActions.Rows[selectedRow1].Cells[4].Text;
}
if (grdActions.Rows[selectedRow1].Cells[5].Text == null || grdActions.Rows[selectedRow1].Cells[5].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[5].Text == " ")
{
txtCompletedDate.Text = string.Empty;
}
else
{
txtCompletedDate.Text = Convert.ToDateTime(grdActions.Rows[selectedRow1].Cells[5].Text).ToString("dd-MMM-yyyy");
}
ddlActionOwner.SelectedValue = grdActions.Rows[selectedRow1].Cells[7].Text;
if (grdActions.Rows[selectedRow1].Cells[8].Text == null || grdActions.Rows[selectedRow1].Cells[8].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[8].Text == " ")
{
txtAssignedTo.Text = string.Empty;
}
else
{
txtAssignedTo.Text = grdActions.Rows[selectedRow1].Cells[8].Text;
}
if (grdActions.Rows[selectedRow1].Cells[9].Text == null || grdActions.Rows[selectedRow1].Cells[9].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[9].Text == " ")
{
lblComments.Visible = false;
txtComments.Visible = false;
}
else
{
lblComments.Visible = true;
txtComments.Visible = true;
txtComments.Text = grdActions.Rows[selectedRow1].Cells[9].Text;
}
I used the Server.HTMLDecode() when transferring the data fromthe gridview to the textboxes. This ensured that all special characters were removed before it was sent back to the textboxes on the form
Related
I'm trying to filter trough by gridview using a textbox when I need to use commas to search for specific items in that grid view
This is my gridview:
As you can see the column Ingredientes contains items separated by commas. What I'm trying to do is if I write in the Ingredientes textbox "repolho,salsa" for example the row appears.
At the moment I can search if the Ingredientes column has just a single item like that one with the "ing"
This is my code
// Procura pelos ingredientes
else if (txtTitulo.Text == "" && txtIngredientes.Text != "")
{
dataGridReceitas.Rows.Clear();
if (File.Exists(receitas))
{
sr = File.OpenText(receitas);
string linha = "";
int x = 0;
while((linha = sr.ReadLine()) != null)
{
string[] campos = linha.Split(';');
if(txtIngredientes.Text == campos[3])
{
dataGridReceitas.Rows.Add(1);
dataGridReceitas[0, x].Value = campos[0];
dataGridReceitas[1, x].Value = campos[1];
dataGridReceitas[2, x].Value = campos[2];
dataGridReceitas[3, x].Value = campos[3];
x++;
}
}
sr.Close();
}
}
You can simply do this :
else if (txtTitulo.Text == "" && txtIngredientes.Text != "")
{
string searchValue = txtIngredientes.Text;
dataGridReceitas.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResult = false;
foreach (DataGridViewRow row in dataGridReceitas.Rows)
{
if (row.Cells[3].Value != null && row.Cells[3].Value.ToString().Equals(searchValue))
{
int rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
valueResult = true;
break;
}
}
if (!valueResult)
{
MessageBox.Show("Unable to find " + searchtextBox.Text, "Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}
I'm having issues with displaying the variable within a Message box. What I want to do is display in a messagebox which Combobox hasn't been filled in, it will display this in a list within the messagebox and then stop the user from saving to the database. The error is stating that it is a use of an unassigned variable but I have assigned it at the top of the 'if' statement.
private void btnSaveDB_Click(object sender, EventArgs e)
{
if (cmbPolType.SelectedItem == null ||
cmbPolNum.SelectedItem == null ||
cmbTPReg.SelectedItem == null ||
cmbLossType.SelectedItem == null ||
cmbLossDesc.SelectedItem == null ||
cmbInsdFault.SelectedItem == null)
{
string polType, polNum, lossType, lossDesc, tpReg, insdFault = null;
if (cmbPolType.SelectedItem==null)
{
polType = "Policy Type";
}
if (cmbPolNum.SelectedItem==null)
{
polNum = "Policy Number";
}
if (cmbLossType.SelectedItem==null)
{
lossType = "Loss Type";
}
if (cmbLossDesc.SelectedItem ==null)
{
lossDesc = "Loss Description";
}
if (cmbTPReg.SelectedItem==null)
{
tpReg = "TP Reg";
}
if (cmbInsdFault.SelectedItem==null)
{
insdFault = "Insd at Fault";
}
MessageBox.Show("You have not selected options for the following: " + lossDesc );
}
No lossDesc is not initialized in that way as well as the other strings variables but the insdFault. (The error message points to lossDesc because is the only one used in the remainder of the code).
Instead of initializing each one, I suggest to use a simple List<string> where you add your error messages and type all of them at the end of the test
List<string> missingData = new List<string>();
if (cmbPolType.SelectedItem == null)
missingData.Add("Policy Type");
if (cmbPolNum.SelectedItem == null)
missingData.Add("Policy Number");
if (cmbLossType.SelectedItem == null)
missingData.Add("Loss Type");
if (cmbLossDesc.SelectedItem == null)
missingData.Add("Loss Description");
if (cmbTPReg.SelectedItem == null)
missingData.Add("TP Reg");
if (cmbInsdFault.SelectedItem == null)
missingData.Add("Insd at Fault");
if(missingData.Count > 0)
{
MessageBox.Show("You have not selected options for the following: " +
Environment.NewLine +
string.Join(Environment.NewLine, missingData.ToArray()));
}
else
{
... save to database ? ....
}
This removes the need to use and initialize a bunch of string variables and uses the string.Join method to get the whole error message in a single string with each error on a separate line.
I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example
here is what i am trying to do, i am using LinQ data context to insert new record to database,
for some reason, my linq showing this error "LinqDataSource 'AirAsiaDC' has no values to insert. Check that the 'values' dictionary contains values." weird part, when i check the record which i tried to insert before, it is there. what i do wrong here?
by the way, here is my code :
protected void DetailsView1_ItemCommand(object sender,
DetailsViewCommandEventArgs e)
{
AirAsiaDCDataContext Linq = new AirAsiaDCDataContext();
try
{
if (e.CommandName == "Edit")
{
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt;
if ((tbname.Text != null) && (tbname.Text != ""))
{
dpt = Linq.departments.Single(d => d.departmentcode == code);
dpt.departmentname = tbname.Text;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.SubmitChanges();
Response.Redirect("Department.aspx");
}
else
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
else if (e.CommandName == "Insert")
{
TextBox tbcode = (TextBox)DetailsView1.FindControl("DeptCode");
TextBox tbname = (TextBox)DetailsView1.FindControl("DeptName");
department dpt = new department();
if (((tbcode.Text != null) && (tbcode.Text != ""))
&& ((tbname.Text != null) && (tbname.Text != "")))
{
dpt.departmentcode = tbcode.Text;
dpt.departmentname = tbname.Text;
dpt.createby = "hendra";
dpt.createdate = DateTime.Now;
dpt.updateby = "hendra";
dpt.lastupdate = DateTime.Now;
Linq.departments.InsertOnSubmit(dpt);
Linq.SubmitChanges();
}
else if ((tbcode.Text == null) || (tbcode.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department code can not be empty";
}
else if ((tbname.Text == null) || (tbname.Text == ""))
{
divError.Visible = true;
lblError.Text = "Department name can not be empty";
}
}
}
catch (Exception ex)
{
divError.Visible = true;
lblError.Text = ex.Message.ToString();
}
}
i even try to use try and catch but get nothing, and my linq keep on showing that error and throw me to error screen.