How to solve System.ArgumentOutOfRangeException - asp.net

I have two page one MasterPage.master and default I think this error for two table[0] I am using in master page,master one poll with data table and default I am using data table for show news when remove data table in page default and run is correct with out error when use two data table I am see error
when run default.aspx this error see:
Specified argument was out of the range of valid values.
Parameter name: index
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index
Source Error:
Line 88: tbl.BorderWidth = 0;
Line 89: tbl.Attributes.Add("Style", "text-align:right");
Line 90: ImageButton ButtonPolls = (ImageButton)tbl.Controls[0];
Line 91: ButtonPolls.ImageUrl = "../images/poll/CastVote.jpg";
Line 92:
this code use MasterPage.master
string strSQL = "select QuestionText from TPollQuestions where Iscurrent=1 and Isarchived=0";
string cmdtext = "";
SqlConnection conn = Conn;
Pollcontrol1.CanVote = true;
if (conn.State == System.Data.ConnectionState.Closed)
conn.Open();
cmdtext = "select QuestionText from TPollQuestions where Iscurrent=1 and Isarchived=0";
cmd = new SqlCommand(cmdtext, conn);
Pollcontrol1.PollQuestion = cmd.ExecuteScalar().ToString();
conn.Close();
cmdtext =
"select optionID,PollID,OptionText,Votes from TPollOptions where pollID in(select PollID from TPollquestions where Iscurrent=1 and Isarchived=0)";
SqlDataAdapter da = new SqlDataAdapter(cmdtext, conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
Pollcontrol1.AddPollAnswer(Convert.ToInt32(dt.Rows[i]["pollID"]), Convert.ToInt32(dt.Rows[i]["optionID"]), dt.Rows[i]["optionText"].ToString(), Convert.ToInt32(dt.Rows[i]["votes"]));
}
TableCell tbl = (TableCell)Pollcontrol1.Controls[0].Controls[Pollcontrol1.Controls[0].Controls.Count - 1].Controls[0];
tbl.BorderWidth = 0;
tbl.Attributes.Add("Style", "text-align:right");
ImageButton ButtonPolls = (ImageButton)tbl.Controls[0];
ButtonPolls.ImageUrl = "../images/poll/CastVote.jpg";
and this code in default.aspx
this datatable for show news when remove getdata(str) is run correct with out error
PagedDataSource pgsource = new PagedDataSource();
int findex, lindex;
DataRow dr1;
static string str = "select * from TNews where 1=1";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//CurrentPage = 0;
GetData(str);
}
}
DataTable GetData(string str)
{
DataTable dtable1= new DataTable();
SqlConnection Conn;
SqlCommand Cmd;
Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["bakerConnectionString"].ToString());
Cmd = new SqlCommand();
Conn.Open();
Cmd.Connection = Conn;
Cmd.CommandText = str;
SqlDataAdapter dap1= new SqlDataAdapter(Cmd);
DataSet ds1 = new DataSet();
dap1.Fill(ds1, "ds1");
pgsource.DataSource = ds1.Tables[0].DefaultView;
DataBind();
return ds1.Tables[0];
}

Looking at the error message I would have to guess that your problem is here:
Line 90: ImageButton ButtonPolls = (ImageButton)tbl.Controls[0];
Also, I see you use the index-based retrieval of controls quite a lot which, is not desirable. Instead, use Control.FindControl method to retrieve the child controls (and, of course, check for nulls).
Let's say your ImageButton has the id _imgButton. To retrieve it from the table use:
var imgButton = tbl.FindControl("_imgButton") as ImageButton;
if(imgButton != null)
{
// your logic here...
}

Related

Error: There is no row at position 0 in asp.net

I wrote this code to get data from gridview to display down the controls, but it failed:
There is no row at position 0.
at line:
txtSTT.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(0).ToString();
Full code:
protected void btnSua_Click(object sender, EventArgs e)
{
string STT = ((LinkButton)sender).CommandArgument;
SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-R8LG380\SQLEXPRESS;Initial Catalog=PHIM;Integrated Security=True");
string query = "SELECT * FROM Trailer WHERE STT = '" + STT + "'";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Trailer");
txtSTT.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(0).ToString();
txtMaTrailer.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(1).ToString();
cmbMaPhim.SelectedValue = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(2).ToString();
txtUrlTrailer.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(3).ToString();
txtGhiChu.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(4).ToString();
txtSTT.ReadOnly = true;
txtSTT.Visible = true;
lbSTT.Visible = true;
}
From the error message, I would say your query is not returning any rows.
Try putting a break point right after the assignment to the queryand copy the string into a query window in SQL Server Management Studio to see if any rows of data come back.
It is probably not returning any rows. Debug your query until you know you have one that returns data.
Also, In addition to putting the contents of this function in a try/catch block, I would wrap all the lines that use ds.Tables["Trailer"].Rows[0] in an if block, something like if(ds.Tables["Trailer"].Rows.Count > 0){

setting a dropdownlist value from database on page load

Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :
<asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
</asp:DropDownList>
and is binded as below :
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
I am not able to set a value in the dropdownlist though.Here is what I have done :
private void ExtractData()
{
string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :
protected void ddlGender_DataBound(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
Now it doesnt throw any error and it doesnt select the value as well.
PS : 1.I have set Autopostback true for the ddl.
2.I am aware of sqlInjection and have made changes to make it look simpler.
My final PageLoad looks like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
ExtractData();
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
}
if (hfImagePath.Value == "" || hfImagePath.Value == "0")
{
imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
hfImagePath.Value = "0";
}
else
{
imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
}
//lblRegistration.Text = Session["Button"].ToString();
}
For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.
Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.
I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).
Try changing:
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
To:
ddlGender.SelectedValue = rdr["Gender"].ToString();
Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
You are trying to set the value to a specific Column, yet you are binding it to a DataSet and not a DataTable. (A DataSet has no columns only DataTables).
Try the following assuming the DataSet has a table returned and the column names match your table structure:
string strDesiredSelection = "Male";
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds.Tables[0];
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
foreach(ListItem li in ddlGender.Items){
if(li.Value.Equals(strDesiredSelection)){
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(li);
}
}

Cannot read the row of the gridview

I am trying to read a gridview row. Here is my code:
protected void allStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Approval")
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = allStudents.Rows[row];
// *** Get the underlying data item - in this case a DataRow
DataRow dr = ((DataTable)this.allStudents.DataSource).Rows[gdrow.DataItemIndex];
// *** Retrieve our context
string courseCode = dr["CourseCode"].ToString();
string courseNumber = dr["CourseNumber"].ToString();
string term = dr["Term"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT RegisterTable.StudentID, StudentTable.Name, StudentTable.Surname FROM RegisterTable JOIN StudentTable ON RegisterTable.StudentID = StudentTable.ID WHERE RegisterTable.CourseCode = #courseCode AND RegisterTable.Term = #term AND RegisterTable.CourseNumber = #courseNumber", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
transcript.DataSource = dt;
transcript.DataBind();
Label1.Visible = true;
Label1.Text = "Students who are registered to " + courseCode + " " + courseNumber + " are listed below:";
}
}
But at the line starting with
DataRow dr = ((DataTable)this.allStudents.DataSource).Rows[gdrow.DataItemIndex];
i get an error saying that "Object reference not set to an instance of an object.". Can anyone tell the problem here?
Note: allStudents is the ID of my gridview
Thanks
That error means of the references in the line is null. That is, you're trying to fetch data from an object, but there is no instantiated object there.
Recommendation: insert a breakpoint at that line. Debug the code. Then, while debugging and on that line, pass the mouse cursor over every name in the line. The debugger will give you rich, detailed information about each and every variable. Once you find which one is null (could be either allStudents or DataSource), you'll be on the right track to solve your problem.
You have to find out whatever is triggering the error for being null, then making sure it's not null when you get to that point in your code.

How to pass a Session to a DataTable?

In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}

sql data reader class

I did sql command with SqlDataReader but I had this error
System.IndexOutOfRangeException: UserName
Page Load event:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("Total", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataReader Dr = Com.ExecuteReader();
if (Dr.Read())
{
string Result= Dr["UserName"].ToString();
Lbltotal.Text = Result;
}
}
}
Stored Procedure:
Alter proc Total
as
begin
select Count (UserName) from Registration
end
Change your storder procedure to:
Alter proc Total
as
begin
select Count (UserName) as UserName from Registration
end
You're not returning any column called UserName - you're just returning a count which has no explicit column name.
If you have something like this - just a single value - you could also use the ExecuteScalar method which will return exactly one value:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
int count = (int)Com.ExecuteScalar();
}
If you insist on using the SqlDataReader, you just need to use a positional parameter:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
using(SqlDataReader Dr = Com.ExecuteReader())
{
if (Dr.Read())
{
string Result= Dr[0].ToString(); // take value no. 0 - the first one
Lbltotal.Text = Result;
}
}
}

Resources