Repeater itemboungf is repeating more than required? - asp.net

The two events are
protected void btnuplaod_Click(object sender, EventArgs e)
{
string filepath = Server.MapPath(#"~/Admin/temp/");
Session["Image"] = Request.Files;
HttpFileCollection uploadedFiles = (HttpFileCollection)Session["Image"];
lblerror.Text = string.Empty;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
try
{
if (userPostedFile.ContentLength > 0)
{
lblerror.Text += "<u>File #" + (i + 1) + "</u><br>";
lblerror.Text += "File Content Type: " + userPostedFile.ContentType + "<br>";
lblerror.Text += "File Size: " + userPostedFile.ContentLength + "kb<br>";
lblerror.Text += "File Name: " + userPostedFile.FileName + "<br>";
userPostedFile.SaveAs(filepath + Path.GetFileName(userPostedFile.FileName));
lblerror.Text += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>";
}
repimages.DataSource = filepath;
Session["repimage"] = userPostedFile.FileName;
repimages.DataBind();
}
catch (Exception Ex)
{
lblerror.Text += "Error: <br>" + Ex.Message;
}
}
}
and
protected void repimages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string filepath = Server.MapPath(#"~/Admin/temp/");
lblerror.Text = string.Empty;
Image img = e.Item.FindControl("postedimage") as Image;
img.ImageUrl = filepath + Session["repimage"];
}
repimages_ItemDataBound(object sender, RepeaterItemEventArgs e) event is repeating 48 times for a single image

repimages_ItemDataBound is invoked when item in your repeater is bound from your datasource. How can it be invoked with a button click?

you have to bind repImages on button click which will internally call repImages_ItemDataBound provided in your aspx you have this OnItemDataBound="repImages_ItemDataBound"

Related

How to get pathname of image from FileUpload in grid view

Hello i have my FileUpload in gridview.I upload image for every row and then click button called UPLOAD. So that it should get image path from every row and upload. Onclick listener for UPLOAD is UploadBtn_onClick.
Code for UploadBtn_onClick is
protected void UploadBtn_onClick(object sender, EventArgs e)
{
foreach (GridViewRow row in StudentGrid.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
try
{
UpdateEmailProperties objUpdateEmailId = new UpdateEmailProperties();
GridViewRow grdrow = (GridViewRow)((FileUpload)sender).NamingContainer;
FileUpload filename = (FileUpload)grdrow.Cells[5].FindControl("fileuploadimages");
objUpdateEmailId.StudId = int.Parse(row.Cells[6].Text);
objUpdateEmailId.Email = row.Cells[3].Text;
objUpdateEmailId.profilepath = "profilepics/" + filename;
int intStatus;
intStatus = Stud.UpdateStudentEmailId(objUpdateEmailId);
if (intStatus != 0)
{
lblWarning.Text = "Updated successfully";
}
else
{
lblWarning.Text = "Failed to Update";
}
}
catch (Exception ex)
{
//LogFile.CreateLog("User", "AddPlacement", ex.Message);
lblWarning.Text = "Error: " + ex.Message.ToString();
}
}
}
}
But i am getting error as
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.FileUpload'
.
I need to fetch name of file returned from loadfile

How to refresh table view from other form controller in javafx?

I have the following method in my UserVerwaltungForm.java:
#FXML
private void clickBtnAdd() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/AddForm.fxml"));
Scene scene = new Scene(root,400,450);
Stage s = new Stage();
s.setScene(scene);
s.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here I open a new AddForm and add something there to the database. I do it this way:
#FXML
private void clickBtnAdd() {
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("insert into tbl values (" + PLACEHOLDER_ID + ", '" + tfUsername.getText() + "', '"
+ tfFirstname.getText() + "', '" + tfLastname.getText() + "', '" + tfPassword.getText() + "', '"
+ tfEmail.getText() + "', " + tfBodyWeight.getText() + ", " + tfBodyHeight.getText() + ", "
+ tfActivityPoints.getText() + ", '" + tfBirthdate.getText() + "')");
stmt.execute("commit");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
DBManager.close(stmt);
DBManager.close(con);
Stage stage = (Stage) btnAdd.getScene().getWindow();
stage.close();
}
If I press the button in the AddForm, I want to call this method from the UserVerwaltungForm:
public void loadDataFromDatabase() {
tbl.getItems().removeAll(tbl.getItems());
setCellConfigurations();
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select b.* from user_bsd b");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
if (rs != null) {
try {
while (rs.next()) {
factory = new Factory(rs);
u = factory.getUser();
tbl.getItems().add(u);
}
} catch (SQLException e) {
System.err.println("Error at rs.next(): " + e.getMessage());
}
}
DBManager.close(rs);
DBManager.close(stmt);
DBManager.close(con);
}
Do you know, where I should call the loadFromDatabase method in the AddFormController after pressing the button?

Cound`t check values in datalist c# asp.net

protected void ImageButton16_Click(object sender, ImageClickEventArgs e)
{
if (Session["login"].ToString() == "true")
{
int i = 0;
foreach (DataListItem Item in DataList1.Items)
{
Label id = (Label)DataList1.Controls[i].FindControl("ID");
Label bidcount = (Label)DataList1.Controls[i].FindControl("Label7");
string email = Session["username"].ToString();
TextBox bid = (TextBox)DataList1.Controls[i].FindControl("TextBox1");
if (bid.Text != "")
{
if (int.Parse(bid.Text) < int.Parse(bidcount.Text))
{
String script = "<SCRIPT LANGUAGE='JavaScript'> ";
script += "AddConfirmbid()";
script += "</SCRIPT>";
Page.RegisterClientScriptBlock("ClientScript", script);
}
else
{
String script = "<SCRIPT LANGUAGE='JavaScript'> ";
script += "invalidbid()";
script += "</SCRIPT>";
Page.RegisterClientScriptBlock("ClientScript", script);
}
}
else
{
String script = "<SCRIPT LANGUAGE='JavaScript'> ";
script += "enterbid()";
script += "</SCRIPT>";
Page.RegisterClientScriptBlock("ClientScript", script);
}
i++;
}
}
else
{
String script = "<SCRIPT LANGUAGE='JavaScript'> ";
script += "login()";
script += "</SCRIPT>";
Page.RegisterClientScriptBlock("ClientScript", script);
}
}
Problem in your code that your are searching textbox in wrong way. I hope blow code will help you out to get textbox correct value.
foreach (DataListItem item in DataList1.Items)
{
TextBox bid = (TextBox)item.FindControl("TextBox1");
string text = bid .text;
// Do whatever you need with that string value here
}

when i press the button the application gives me an error "index out of range" [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In this code I dynamically create checkboxes which I populate with data from my database.
My intention is when I press the btnProba button to show the text property only from the selected checkboxes. But it gives me an error in this row saying that index is out of range! I can't explain why.
lblProba.Text = myche[0];
public partial class FormEGN : System.Web.UI.Page
{
string mynewstring;
List<string> myche = new List<string>();
CheckBoxList mycheckbox = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
mynewstring = (string)Session["id2"];
// lblProba.Text = mynewstring;
if(!IsPostBack)
{
ddlNumberTourists.Items.Add("1");
ddlNumberTourists.Items.Add("2");
ddlNumberTourists.Items.Add("3");
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
lblProba.Text = myche[0];
}
protected void btnReserve_Click(object sender, EventArgs e)
{
string num = Request.QueryString["ExcursionID"];
Response.Redirect(String.Format("ClintsInformation.aspx?Excursiondate_ID={0}",num));
}
}
}
The function ddlNumberTourists_SelectedIndexChanged is the one that set the myche when is find some selected, but the data is lost on the second call where is the
protected void btnProba_Click(object sender, EventArgs e)
{
// here is the issue
lblProba.Text = myche[0];
}
The two calls are happening on different post back.
You need to call the ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e) on button click and not on every change of the dropdownlist, eg I rename it to CheckWhatIsSelected() and here is the code:
protected void CheckWhatIsSelected()
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "??????????? ??????" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
CheckWhatIsSelected();
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}
One other possible solution is to save the myche on viewstate.
Other solution using the ViewState. You use the ViewState to store your selection and you have it after the post back. Do not forget to clear your list on ddlNumberTourists_SelectedIndexChanged
List<string> myche
{
get
{
if (!(ViewState["cMyChe"] is List<string>))
{
// need to fix the memory and added to viewstate
ViewState["cMyChe"] = new List<string>();
}
return (List<string>)ViewState["cMyChe"];
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
// double check if have something on the list
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}

Object reference not set to an instance of an object

I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.

Resources