Generation random number for the text entered in the textbox - asp.net

I have a textbox,when a user enters any number(say 3) in the textbox, that many random numbers should be generated.This is what I have done so far but its generating the same random number for all 3(or as many as the user enters) records.
protected void Page_Load(object sender, EventArgs e)
{
for (Int32 x = 0; x <= 50; x++)
{
txtRandomNumber.Text = GetRandomString(x);
}
}
public string GetRandomString(int seed)
{
const string alphabet = "R";
Random rnd = new Random((seed + DateTime.Now.Millisecond));
string result = rnd.Next(10000, 99999).ToString();
string alpha = alphabet.Substring(rnd.Next(alphabet.Length - 1));
int replacementIndex = rnd.Next(0);
result = result.Remove(replacementIndex, 1).Insert(replacementIndex, alpha);
return result;
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 1; i <= int.Parse(txtNoOfPin.Text); i++)
{
if (i == 1)
{
string strConnection = ConfigurationManager.ConnectionStrings["ReliableLife"].ToString();
SqlConnection con = new SqlConnection(strConnection);
string sqlQuery = "insert into AllotPin(NoOfPin,PinNumber) values(#NoOfPin,#PinNumber)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#NoOfPin", int.Parse(txtNoOfPin.Text));
cmd.Parameters.AddWithValue("#PinNumber", txtRandomNumber.Text);
cmd.ExecuteNonQuery();
}
else
{
string r_no = "";
for (Int32 x = 0; x <= 50; x++)
{
r_no = GetRandomString(x);
//Response.Write(GetRandomString(x) + "<br />");
}
string strConnection = ConfigurationManager.ConnectionStrings["ReliableLife"].ToString();
SqlConnection con = new SqlConnection(strConnection);
string sqlQuery = "insert into AllotPin(NoOfPin,PinNumber) values(#NoOfPin,#PinNumber)";
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#NoOfPin", int.Parse(txtNoOfPin.Text));
cmd.Parameters.AddWithValue("#PinNumber", txtRandomNumber.Text);
cmd.ExecuteNonQuery();
}
}
}
Please Help,Thanks

try to apped random number to textbox
for (Int32 x = 0; x <= 50; x++)
{
txtRandomNumber.Text = x +" "+ GetRandomString(x) +" "+ txtRandomNumber.Text;
}
The program has some redundancy but it will generate random numbers as per your requirement.

Thanks for the help.
I solved the problem doing this in the else part of the code:
for (Int32 x = 0; x <= 50; x++)
{
r_no = GetRandomString(x);
txtRandomNumber.Text = r_no;
}
This gave the output as required.

Related

Oracle "UPDATE" command returns 0 rows affected in my ASP .NET application but the SQL statement itself works in PL/SQL

I have this ASP.NET project working with Oracle, I have the following code for operating the DB:
public int cmd_Execute_Orcl(string strSql, params OracleParameter[] paramArray)
{
OracleCommand myCmd = new OracleCommand();
try
{
myCmd.Connection = myOrclConn;
myCmd.CommandText = strSql;
foreach (OracleParameter temp in paramArray)
{
myCmd.Parameters.Add(temp);
}
ConnectionManage(true);
int i = myCmd.ExecuteNonQuery();
myCmd.Parameters.Clear();
return i;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myCmd.Dispose();
ConnectionManage(false);
}
}
"ConnectionManage()" turns on or off the connection, the following code is from data access layer of the program:
public string Edit_DAL(string id, string jh, string jz, string jd, string wd, string gzwz, string qxlx, string sx, string jx, string jb, string cfdd, string zjqssj, string zjzzsj, string bz)
{
string sql = "update JH set jh = :jh, jz = :jz, wd = :wd, jd = :jd, gzwz = :gzwz, qxlx = :qxlx, sx = :sx, jx = :jx, jb = :jb, cfdd = :cfdd, zjqssj = TO_DATE(:zjqssj, 'yyyy-mm-dd hh24:mi:ss'), zjzzsj = TO_DATE(:zjzzsj, 'yyyy-mm-dd hh24:mi:ss'), bz = :bz where ID = :idy";
string result = null;
{
String[] temp1 = zjqssj.Split('/');
String[] temp2 = zjzzsj.Split('/');
string tempString = "";
if (temp1[2].Length < 2)
{
temp1[2] = temp1[2].Insert(0, "0");
}
for (int i = 0; i < temp1.Length; i++)
{
if (i != 0)
{
temp1[i] = temp1[i].Insert(0, "/");
}
tempString += temp1[i].ToString();
}
zjqssj = tempString;
tempString = "";
if (temp2[2].Length < 2)
{
temp2[2] = temp2[2].Insert(0, "0");
}
for (int i = 0; i < temp2.Length; i++)
{
if (i != 0)
{
temp2[i] = temp2[i].Insert(0, "/");
}
tempString += temp2[i].ToString();
}
zjzzsj = tempString;
tempString = "";
}
OracleParameter[] pars ={
new OracleParameter(":idy",id),
new OracleParameter(":jh",jh),
new OracleParameter(":jz",jz),
new OracleParameter(":jd",jd),
new OracleParameter(":wd",wd),
new OracleParameter(":gzwz",gzwz),
new OracleParameter(":qxlx",qxlx),
new OracleParameter(":sx",sx),
new OracleParameter(":jx",jx),
new OracleParameter(":jb",jb),
new OracleParameter(":cfdd",cfdd),
new OracleParameter(":zjqssj",(zjqssj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":zjzzsj",(zjzzsj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":bz",bz)
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
result = "ok";
}
catch (Exception ex)
{
result = "no" + "=" + ex.Message + "\n" + ex.StackTrace;
}
return result;
}
Here's where the strange thing happens, when I hit this part of the code, there's no exception, it returns 0, no rows affected, all the values of the parameters are normal, with expected value, then I tried to run the command in PL/SQL and it works, the row is correctly updated, delete function is also referencing the same "cmd_Execute_Orcl" method and it works just fine, and for the other object the edit function is working perfectly, I am posting the code below:
public string Edit(string OriginalId, string EditUserAccount, string EditUserName, string EditUserMobile, string EditDeptId, string EditRoleId, string EditRoleName)
{
string sql = "update AuthUser set UserAccount=:EditUserAccount, UserName=:EditUserName, UserMobile=:EditUserMobile, DepartmentId=:EditDeptId, RID=:EditRoleId, RoleName=:EditRoleName where ID=:OriginalId";
OracleParameter[] pars ={
new OracleParameter(":EditUserAccount",EditUserAccount),
new OracleParameter(":EditUserName",EditUserName),
new OracleParameter(":EditUserMobile",EditUserMobile),
new OracleParameter(":EditDeptId",EditDeptId),
new OracleParameter(":EditRoleId",EditRoleId),
new OracleParameter(":EditRoleName",EditRoleName),
new OracleParameter(":OriginalId",OriginalId),
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
return "ok";
}
catch (Exception ex)
{
string test = ex.Message;
return "no";
}
}
In the expected table, column ID is nvarchar2 with default value of sys_guid(), column ZJQSSJ and column ZJZZSJ is of type date, all other columns are of type varchar2, I have also tried executing "COMMIT" and reformating data for date, but the same problem is still there, plz help...

Gridview not populating by datatable

Below is the code where The four columns("Challan Number","Proposal Number","CTS Number" and "Amount") is obtained from Sql-Database, and the ("Land" and "Ward") values are obtained from respective methods. The values obtaines are correct but still the "ChallanGridview" is not getting populated.
The datarow "dr1" gets populated with the correct required values, but the "ChallanGridview" doesn't shows anything.
public void FillChallanGrid()
{
string query = string.Empty;
string cs = ConfigurationManager.ConnectionStrings["ConStrg"].ConnectionString;
query = CtrlChallenSearch1.GetChallanQuery();
using(SqlConnection con=new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds,"entry");
int x = ds.Tables["entry"].Rows.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Challan Number");
dt.Columns.Add("Proposal Number");
dt.Columns.Add("CTS Number");
dt.Columns.Add("Amount");
dt.Columns.Add("Land");
dt.Columns.Add("Ward");
for(int i=0;i<x;i++)
{
DataRow dr = ds.Tables["entry"].Rows[i];
DataRow dr1 = dt.NewRow();
dr1["Challan Number"] = dr["ReceiptNo"].ToString();
dr1["Proposal Number"] = dr["ProposalNo"].ToString();
dr1["CTS Number"] = dr["CTSNo"].ToString();
dr1["Amount"] = dr["Amount"].ToString();
dr1["Land"] = GetLand(dr["ProposalNo"].ToString());
dr1["Ward"]=GetWard(dr["ProposalNo"].ToString());
dt.Rows.Add(dr1);
}
ChallanGridView.DataSource = dt;
ChallanGridView.DataBind();
}
}
private object GetLand(string ProposalNumber)
{
string retvalue = string.Empty;
if (ProposalNumber != "" || ProposalNumber != null || ProposalNumber != string.Empty)
{
string[] splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[1];
}
return retvalue;
}
private object GetWard(string ProposalNumber)
{
string retvalue = string.Empty;
string[] splittedvalue = new string[3];
splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[0];
return retvalue;
}
protected void Button1_Click(object sender, EventArgs e)
{
FillChallanGrid();
}
Its solved, I just deleted the present gridview and added another fresh one,
don't know how and why, but the error was gone.
btw thnks Asif.Ali!

SQL MDF Database every cell displays: "System.__ComObject"

When I execute this program the Excel part generates and string array: cellValue just fine.
When it inserts into the SQL MDF Database: MDFExcel every cell displays: "System.__ComObject".
How do you display the string value instead of the "System.__ComObject"?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("#col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("#col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
Worksheet.Cells returns a Range and not a single value - and a Range (an RCW object) does not implemented a sensible ToString; thus it defaults to the "System.__ComObject" value shown.
Use the Text property of the Range, eg.
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
While this should fix the immediate problem, it is also an inefficient process. See this response (using the Value/Value2 property) for how to access the Range values as a 2-dimensional array and reduce excessive range-slicing.

Index out of range, error

my code sometimes throw error but sometimes not.
Error:
Index out of range.
code:
protected void btnGenerateReport_Click(object sender, EventArgs e)
{
GridViewSmsComplaints.DataBind();
dtRoom.Columns.Add(new DataColumn("ID", typeof(string)));
dtRoom.Columns.Add(new DataColumn("RecievingDate", typeof(string)));
dtRoom.Columns.Add(new DataColumn("FromMobileNo", typeof(string)));
dtRoom.Columns.Add(new DataColumn("Message", typeof(string)));
dtRoom.Columns.Add(new DataColumn("IsComplaint", typeof(short)));
for (int i = 0; i <= 5; i++)
{
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
ManageRecievedMessage mngRecMsg = new ManageRecievedMessage();
DropDownList IsValid = (DropDownList) GridViewSmsComplaints.Rows[i].FindControl("ddlValidity");
short IsComplaint;
if (IsValid.SelectedValue == "1")
{
IsComplaint= Convert.ToInt16(IsValid.SelectedValue.ToString());
mngRecMsg.UpdateSmsComplaintValidity(ID, 1);
DataRow datarw = null;
datarw = dtRoom.NewRow();
datarw[0] = GridViewSmsComplaints.Rows[i].Cells[0].Text;
datarw[1] = GridViewSmsComplaints.Rows[i].Cells[1].Text;
datarw[2] = GridViewSmsComplaints.Rows[i].Cells[2].Text;
datarw[3] = GridViewSmsComplaints.Rows[i].Cells[3].Text;
datarw[4] = IsComplaint; //Convert.ToInt16(GridViewSmsComplaints.Rows[i].Cells[4].Text);
dtRoom.Rows.Add(datarw);
}
else if(IsValid.SelectedValue != "1" )
{
IsComplaint= Convert.ToInt16(IsValid.SelectedValue.ToString());
mngRecMsg.UpdateSmsComplaintValidity(ID, IsComplaint);
}
}
GridViewSmsComplaints.DataBind();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/Report_SmsComplaintsByDate.rdlc");
if (dtRoom.Rows.Count <= 0)
{
HiddenFieldSetMessage.Value = "NotExists";
HiddenFieldShowMessage.Value = "True";
ReportViewer1.Visible = false;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = false;
}
else
{
ReportDataSource rpds = new ReportDataSource("DataSet1", dtRoom);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rpds);
ReportViewer1.Visible = true;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = false;
}
}
at this line:
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
my gridview is displaying two rows, among whihc i have to validate whether VALID (1) or invalid (0) from dropdown but it throws error but sometimes it doesn't.
ERROR:
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
Your grid doesn't always have at least 5 rows so trying to index into the Rows collection causes your out of bounds exception. Looks a little odd to me that you're currently exepcting exactly 5 rows but if you're getting this error it is not the case.
To avoid the error change your code to this:
for (int i = 0; i < GridViewSmsComplaints.Rows.Count; i++)
{
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
....

how to find which imagebutton was clicked?

I have created a function which displays a bus seat layout, dynamically. Now after adding all this dynamically created table and cells into a tag, I want to know which imagebutton was clicked.I have also mentioned proper ID to each imagebutton in cell.
public void DisplaySeatLayout(ListBus _listBus) {
//fetching data from database
SeatBUS _seatBUS = new SeatBUS();
DataTable dt = _seatBUS.GetAllSeatByBusRouter(_listBus);
//Layout generation code
ImageButton img ;
HtmlTable table = new HtmlTable();
table.Attributes.Add("runat", "server");
table.Attributes.Add("id", "LayoutTable");
HtmlTableRow [] tr = new HtmlTableRow[] { new HtmlTableRow(), new HtmlTableRow(), new HtmlTableRow(),new HtmlTableRow(),new HtmlTableRow()};
HtmlTableCell tc = null;
int SeatNo=0;
//Getting Total no of seats.
int MaxSeatNo = dt.Rows.Count;
//Iterating datatable
//Displaying labels for displaying column names in the table
for (int columnCounter = 0; columnCounter < 8; columnCounter++){
for (int rowCounter = 0; rowCounter < 5; rowCounter++){
if (SeatNo < MaxSeatNo){
if (rowCounter == 2 && columnCounter < 7){
tc = new HtmlTableCell();
Label lbl = new Label();
lbl.Text = "";
lbl.ID = "lbl " + rowCounter.ToString() + columnCounter.ToString();
tc.Controls.Add(lbl);
tr[rowCounter].Controls.Add(tc);
//reducing seat number for sake of sequence.
}
else{
//adding label in each cell.
tc = new HtmlTableCell();
Label lbl = new Label();
lbl.Text = dt.Rows[SeatNo]["NumberSeat"].ToString();
lbl.ID = "lbl " + rowCounter.ToString() + columnCounter.ToString();
tc.Controls.Add(lbl);
//adding imagebutton in each cell .
img = new ImageButton();
img.Attributes.Add("type", "image");
img.Attributes.Add("id", rowCounter.ToString());
img.CssClass = "seatRightMostRow1";
img.ImageUrl = "../Images/available_seat_img.png";
img.ID = dt.Rows[SeatNo]["NumberSeat"].ToString();
img.Click += new ImageClickEventHandler(Imagebutton_Click);
tc.Controls.Add(img);
tr[rowCounter].Controls.Add(tc);
SeatNo++;
}
}//SeatNo < MaxSeatNo
table.Controls.Add(tr[rowCounter]);
}
seatArranngement.Controls.Add(table);
}
}
this is complete code after suggestion.
function that is displaying dynamic table is inside Page_load
protected void Page_Load(object sender, EventArgs e)
{
_listBusBUS = new ListBusBUS();
_routerBUS = new RouterBUS();
_listBus = new ListBus();
_promoteBUS = new PromoteBUS();
if (!Page.IsPostBack)
{
LoadData();
}
DisplaySeatLayout();
}
Also here i have copied code in prerender
protected override void OnPreRender(EventArgs e)
{
if (MultiView1.ActiveViewIndex == 1)
{
int listBusID = int.Parse(hdlListBusID.Value.ToString());
_listBus = _listBusBUS.GetAllListBusById(listBusID);
litListBusID.Text = _listBus.ListBusID.ToString();
litRouterID.Text = _listBus.RouterID.ToString();
litArrival.Text = _listBus.Arrival.ToString();
litDeparture.Text = _listBus.Departure.ToString();
litPrice.Text = _listBus.Price.ToString();
}
else if (MultiView1.ActiveViewIndex == 2)
{
//original code starts from here
litListBusIDS.Text = litListBusIDS.Text;
litRouterIDS.Text = litRouterID.Text;
litArrivalS.Text = litArrival.Text;
litDepartureS.Text = litDeparture.Text;
litSeat.Text = hdlSeat.Value;// chkSeat.SelectedItem.Text;
litPrices.Text = litPrice.Text;
//hdlSeat.Value = chkSeat.SelectedItem.Text.ToString();
}
else if (MultiView1.ActiveViewIndex == 3)
{
litCustomerNameStep4.Text = txtcustomername.Text;
litSeatStep4.Text = litSeat.Text;
litPriceStep4.Text = litPrices.Text;
}
base.PreRender(e);
}
Also, layout is getting created twice if i click on any imagebutton.
All you have to do is get the value that you already placed inside the "id" attribute.
You can do this inside the Imagebutton_Click even you created:
protected void Imagebutton_Click(object sender, EventArgs e)
{
ImageButton b = sender as ImageButton;
string id = b.Attributes["id"]; // Returns the id
}

Resources