Cound`t check values in datalist c# asp.net - 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
}

Related

Repeater itemboungf is repeating more than required?

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"

Changing the parameter in sql query of ASP.NET page - with button_click event, sql query in every button click

I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV

Error reading words in the text file

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!
Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

How to get the data of a specific column from an excel file?

Hi I've an excel file which looks like this
id name age phne no and like this i have 35 columns.........
I'm using a webapplication for this in which I've a fileupload control,a button and two textboxes
fileuploadcontrol
button
textbox1
textbox2
Now when I upload the excel file on button click it should read complete file .........
and when I enter the required column in the textbox1 I get those column details only its like this
textbox1(c1,c4,c5,c30) I sholud get only those column details and in the other text box if I enter the location to be saved it should be saved in that location can any one help me with this I had finished till file uploading and reading.....all I need is how to evaluate those textboxes to get my required data
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/xlsx")
{
path = Server.MapPath(".") + "\\inputfiles\\" + Guid.NewGuid() + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(path);
Label1.Text = "File Uploaded Successfully...";
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
}
else
Label1.Text = "Upload .xlsx File";
}
else
Label1.Text = "Upload file";
}
Check this:
Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET
You can specify what columns you need to read on select query.
Regards
I got the answer myself .......ty for tryin to helpin me m postin my code if any needs in any case........
protected void btns_Click(object sender, EventArgs e)
{
string path = string.Empty;
location = Textbox2.Text;
if (fup1.HasFile)
{
try
{
path = Server.MapPath(".") + "\\uploadedfiles\\" + Guid.NewGuid() + fup1.FileName;
fup1.PostedFile.SaveAs(path);
lbl5.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lbl5.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
excelfile(path);
}
}
void excelfile( string path)
{
string readfile = path;
// initialize the Excel Application class
Excel.Application app = new Excel.Application();
//Excel.Worksheet NwSheet;
Excel.Range ShtRange;
// create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(readfile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 1;
System.Text.StringBuilder sb = new StringBuilder();
try
{
string[] values = Textbox1.Text.Split(new char[] { ',' });
int[] colindexs = new int[values.Length];
for (int i = 0; i < values.Length; i++)
{
colindexs[i] = Convert.ToInt16(values[i]);
}
while (((Excel.Range)workSheet.Cells[index, 1]).Value2 != null)
{
string str = "";
foreach (int col1 in colindexs)
{
str = str + Convert.ToString(((Excel.Range)workSheet.Cells[index, col1]).Value2) + ",";
}
str = str.Substring(0, str.Length - 1);
sb.Append(str);
sb.Append(Environment.NewLine);
index++;
}
Writetofile(sb.ToString());
ShtRange = workSheet.UsedRange;
}
catch (Exception ex)
{
app.Quit();
lbl5.Text=ex.Message;
}
}
void Writetofile(string content)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(location, true))
{
sw.Write(content);
sw.Flush();
}
}
}

Dynamically adding a commandbutton in ASP.NET

I have a page with a dynamically created command button.
I need to dynamically wire up a click event so I can grab the CommandArgument of the clicked button.
Button b = new Button();
b.ID = "btnTrigger2";
b.CssClass = "hiddenBtn";
b.CommandName = "lbl3";
b.Click += new EventHandler(btnTrigger_Click);
The problem is the last line - I can't wire up an EventHandler this way - I need to use the standard EventArgs instead of CommandEventArgs.
Anyone have any suggestions on getting this to work? There's got to be a way...
EDIT
Figured I'd post the code that finally worked in case anyone else tries to do the same thing.
`string tabLoadedScript = string.Empty;
string postBackScript = string.Empty;
string script = " <script language='javascript' type='text/javascript'>" + System.Environment.NewLine;
script += "function clientActiveTabChanged(sender, args) {" + System.Environment.NewLine;
int i = 0;
foreach(TabPanel tp in tc1.Tabs)
{
Button b = new Button();
b.ID = "btn" + tp.ClientID;
b.CssClass = "hiddenBtn";
b.CommandName = tp.ID;
b.Command += btnTrigger_Click;
this.form1.Controls.Add(b);
AsyncPostBackTrigger trg = new AsyncPostBackTrigger();
trg.ControlID = "btn" + tp.ClientID;
tabLoadedScript += "var isTab" + tp.ClientID + "loaded=$get('" + tp.Controls[0].ClientID + "');" + System.Environment.NewLine;
postBackScript += "if(!isTab" + tp.ClientID + "loaded && sender.get_activeTabIndex() == " + i + ") {" + System.Environment.NewLine;
postBackScript += "__doPostBack('" + b.ClientID + "','');}" + System.Environment.NewLine;
i++;
}
script += tabLoadedScript;
script += postBackScript;
script += "}" + System.Environment.NewLine;
script += "</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "cs", script, false);
protected void btnTrigger_Click(object sender, CommandEventArgs e)
{
System.Threading.Thread.Sleep(2500);
Panel ctrl = (Panel) FindControlRecursive(this, "pnl" + e.CommandName);
ctrl.Visible = true;
}
public static Control FindControlRecursive(Control Root, string Id)
{
if(Root.ID == Id)
return Root;
foreach(Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if(FoundCtl != null)
return FoundCtl;
}
return null;
}
`
You can still access the CommandArgument using the the first argument passed to the click handler.
Something like:
protected void btnTrigger_Click(object sender, EventArgs e)
{
Button btnTrigger = sender as Button;
String commandArgument = btnTrigger.CommandArgument;
.
.
.
.
//Other code....
}
You need to use the Command event instead of the Click event. Also, assuming you're using a recent version of Visual Studio and .Net, you can simply change the event registration from
b.Click += new EventHandler(btnTrigger_Click);
to
b.Command += btnTrigger_Click
The explicit typing of the delegate is redundant and will be inferred by the compiler. You can now change the signature of your event handler to:
protected void btnTrigger_Click(object sender, CommandEventArgs e)
And the code should work as desired.
Unfortunately, the default code snippets in Visual Studio still generate this old-style event listener code.

Resources