Error: There is no row at position 0 in asp.net - 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){

Related

No values output to txtField while reading from SQL Server database in ASP.NET

I am trying to simply read data from my SQL Server database and input them into text fields on a webform.
I can't figure out what I'm missing but everything compiles smoothly and runs but my text fields remain empty.
protected void Page_Load(object sender, EventArgs e)
{
String index = Request.Form["indexTb"];
string constr = ConfigurationManager.ConnectionStrings["TravelLogConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID='" + Convert.ToInt32(index) + "'";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}
}
You're calling the reader2.Read(); twice - once in the while loop, once just below:
while (reader2.Read())
{
reader2.Read(); // <=== WHY call .Read() a second time ?!?!!?!
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
That's both unnecessary, and could lead to no results being returned.
If your query only returns one row, the .Read() in the while loop would read that row and return it, but then the next line does another Read(), which would not return any data (since the first and only row has already been read).
Just remove that unnecessary second call to .Read() and I bet your data will begin to show up!
And to fix that glaring SQL injection - use parametrized queries! as one should always do anyway!
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID = #Id;";
SqlCommand com = new SqlCommand(selectSql, con);
com.Parameters.Add("#Id", SqlDbType.Int).Value = Convert.ToInt32(index);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
// REMOVE THIS reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}

search data from database asp.net

protected void Button1_Click(object sender, EventArgs e)
{
string db = "Data Source=DESKTOP-R6H3RTP;Initial Catalog=AdmitDB; Integrated Security= true;";
SqlConnection mycon = new SqlConnection(db);
mycon.Open();
String query = "select * from tblPatient where PhoneNo like '"+TextBox1.Text+"%'";
SqlCommand cmd = new SqlCommand(query, mycon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (cmd.ExecuteNonQuery() > 0)
{
lblName.Visible = true;
lblId.Visible = true;
lblPNo.Visible = true;
lblDOB.Visible = true;
lblName.Text = "PName";
lblId.Text = "Pid";
lblPNo.Text = "PhoneNo";
lblDOB.Text = "PDOB";
}
else
{
lblNotFound.Visible = true;
}
}
i'm searching from database but just else statement executes don't know why it's not get data from database, if any kind of error then help me please
i think you don't need if (cmd.ExecuteNonQuery() > 0). the cmd executes automatically. you want to check the tables in the dataset.
// check the first table for rows.
if(ds.Tables[0].HasRows())
{
// success. now you can work with the table.
}
ExecuteNonQuery method returns the number of row that were modified by the query. Since SELECT query doesn't modify anything in the database - you get 0.
You should modify your query with a COUNT(*) function:
String query = "select COUNT(*) from tblPatient where PhoneNo like '"+TextBox1.Text+"%'";
Then you can get that value with ExecuteScalar():
if (cmd.ExecuteScalar() > 0)

How to solve System.ArgumentOutOfRangeException

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...
}

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.

Update in GridView "No value given for one or more parameters"

I have this code (below) and I am getting the following error:
No value given for one or more parameters
But when it is run again, values are shown updated for 'RateCenterName', 'QuantityThreshold', 'RateCenterID' but not for 'Province'
The code:
string updateSql = "UPDATE RateCenters SET RateCenterName = ?, Province=?, QuantityThreshold = ?" + " WHERE RateCenterID= ?";
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("DropDownList2"); // assigning the dropdownlist item to 'ddl'
TextBox rateCenterName = (TextBox)row.FindControl("txtRateCenterName"); // assigning textbox input item
TextBox quantityThreshold = (TextBox)row.FindControl("txtQuantityThreshold"); // assigning textbox input item
Label ratecenterid = (Label)row.FindControl("Label1"); // assigning the label value
//OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\My Documents\Visual Studio 2010\Projects\BillingApplicationNew\BillingApplicationNew\App_Data\db1.mdb;Persist Security Info=False");
OleDbCommand cmd = null;
try
{
cmd = new OleDbCommand(updateSql, conn);
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = rateCenterName.Text;
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = ddl.SelectedItem.Text;
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = Convert.ToUInt32(quantityThreshold.Text);
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = Convert.ToInt32(ratecenterid.Text);
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
//GridView1.EditIndex = -1; //refreshing
//GridView1.DataBind();
}
catch (OleDbException ex)
{
throw (ex);
}
finally
{
conn.Close();
conn.Dispose();
}
}
Can anyone see what's wrong?
Moderator edit:
He solved the problem, but his solution is deep inside one of the comment threads:
I got it, i removed the Row updating event and just tried it once
again without adding that event.
I think he means: he took this code out of the RowUpdating event handler and put it elsewhere.
there might be Problem in your code because you are trying to edit access database and you are writing code of sqldatabase....
You Update Statement code
string updateSql = "UPDATE RateCenters SET RateCenterName =?, Province=? ,
QuantityThreshold = ? WHERE RateCenterID= ?";
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("RateCenterName", str2);
cmd.Parameters.AddWithValue("Province", str3);
cmd.Parameters.AddWithValue("QuantityThreshold ", str4);
cmd.Parameters.AddWithValue("RateCenterID", str5);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have a missing space before WHERE when you are building your SQL.
Line 2 in your sample code.
"WHERE RateCenterID= #RateCenterID"; // this the error. you need to provide space before where
you need to add space before Where .
this you should try
string updateSql = "UPDATE RateCenters SET RateCenterName = #RateCenterName, Province=
#Province, QuantityThreshold = #QuantityThreshold" + " WHERE RateCenterID= #RateCenterID";
The most likely problem is passing a null value to either RateCenterName or Province.
What happens when you try this:
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = "rateCenter";
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = "ddl";
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = 0;
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = 1;

Resources