Error cannot find Column 2 dr = ds.Tables[0].Rows[0] - asp.net

I've been searching for an answer since this code was working fine like an hour ago and I did not make any editting so it turns a little confuse to recognize the error if any of you could help I would appreciate it much. Thanks in advance.
I've checked and there are no errors on the SQL query, as I said it was working fine dr is defined globally as:
DataRow dr = new DataRow();
and MyTable is defined globally also as
DataTable MyTable = new DataTable();
here's the related code:
sentencia = "select * from Facturas" + Session["sociotabla"].ToString() + " where IdFactura = " + Session["idFactura"].ToString();
ds = bd.Consulta(sentencia);
if (ds != null)
{
dr = MyTable.NewRow();
dr = ds.Tables[0].Rows[0];
LimpiarControles();
tbFactura.Text = dr[0].ToString();
ListItem li;
for (int i = 0; i < ddlCliente.Items.Count; i++)
{
li = ddlCliente.Items[i];
if (li.Value == dr[2].ToString()) //Error here Cannot find Column 2
{
ddlCliente.SelectedIndex = i;
Session["idCliente"] = dr[2].ToString();
break;
}
}

Related

How to perform Rollback in asp.net when using Stored Procedure

I want to insert data into 12 different tables on a single click of a button. For this I am using single stored procedure. But my problem is when I am doing this and if there is any exception occurs my data is getting inserted partially i.e values is getting inserted in some tables and some remains empty and due to this problem occurs since all are related to one another. So wanted to know is there any way to perform Rollback so that if any exception occurs entire query is rolled back and data is not inserted in any of the table.
This is the code I am currently using for inserting values.
public int Sp_InsertUpdateDelete(string s, SqlParameter[] spa)
{
SqlConnection sc = new SqlConnection(cs);
sc.Open();
SqlCommand scm = new SqlCommand(s, sc);
scm.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter sql in spa)
{
scm.Parameters.Add(sql);
}
int k = scm.ExecuteNonQuery();
sc.Close();
return k;
}
protected void btnHostingSubmit_Click(object sender, EventArgs e)
{
string select = "select * from tbl_Hosting where Customer_Id='" + ddlCustomerName.SelectedValue + "'";
DataSet s = gs.select(select);
if (s.Tables[0].Rows.Count > 0)
{
Response.Write("<script>alert('Customer Already Exist');</script>");
}
else
{
if (ddlHosting.SelectedValue == "Yes")
{
SqlParameter[] spa = new SqlParameter[29];
spa[0] = new SqlParameter("#Customer_Id", Convert.ToInt16(ddlCustomerName.SelectedValue));
spa[1] = new SqlParameter("#Type", 2);
//Hosting
if (txtHostingSDate.Text == "" || txtHostingSDate.Text == null)
{
spa[2] = new SqlParameter("#Hosting_start_date", null);
}
else
{
spa[2] = new SqlParameter("#Hosting_start_date", Convert.ToDateTime(txtHostingSDate.Text));
}
if (txtHosingEDate.Text == "" || txtHosingEDate.Text == null)
{
spa[3] = new SqlParameter("#Hosting_end_date", null);
}
else
{
spa[3] = new SqlParameter("#Hosting_end_date", Convert.ToDateTime(txtHosingEDate.Text));
}
spa[4] = new SqlParameter("#Hosting_provider", ddlHostingPro.SelectedItem.ToString());
spa[5] = new SqlParameter("#Hosting_type", ddlHostingType.SelectedItem.ToString());
spa[6] = new SqlParameter("#Hosting_server", ddlHostingServer.SelectedItem.ToString());
spa[7] = new SqlParameter("#Hosting_total_id", Convert.ToInt16(txtHostingId.Text));
spa[8] = new SqlParameter("#Hosting_mail_tracking", ddlHostingMailTracking.SelectedItem.ToString());
spa[9] = new SqlParameter("#Hosting_mail_tracking_users", Convert.ToInt16(txtHostingMtUser.Text));
spa[10] = new SqlParameter("#Hosting_dns", ddlHostingDns.SelectedItem.ToString());
spa[11] = new SqlParameter("#Hosting_mail", ddlHostingMail.SelectedItem.ToString());
spa[12] = new SqlParameter("#Hosting_web", ddlHostingWeb.SelectedItem.ToString());
spa[13] = new SqlParameter("#Hosting_manage_dns", ddlHostingMngDns.SelectedItem.ToString());
if (ddlHostingDns.SelectedValue == "No" && (ddlHostingMail.SelectedValue == "Yes" || ddlHostingWeb.SelectedValue == "Yes"))
{
spa[14] = new SqlParameter("#Hosting_ns1", txtNS1.Text);
spa[15] = new SqlParameter("#Hosting_ns2", txtNS2.Text);
}
else
{
spa[14] = new SqlParameter("#Hosting_ns1", ddlHostingNS1.SelectedItem.ToString());
spa[15] = new SqlParameter("#Hosting_ns2", ddlHostingNS2.SelectedItem.ToString());
}
spa[16] = new SqlParameter("#Hosting_rec_ip", txtHostingARecordIp.Text);
spa[17] = new SqlParameter("#Hosting_mx_rec1", txtMXRecord1.Text);
spa[18] = new SqlParameter("#Hosting_mx_rec2", txtMXRecord2.Text);
spa[19] = new SqlParameter("#Hosting_mx_ip1", txtHostingMxIp1.Text);
spa[20] = new SqlParameter("#Hosting_space", ddlHostingSpace.SelectedItem.ToString());
spa[21] = new SqlParameter("#Hosting_mx_ip2", txtHostingMxIp2.Text);
spa[22] = new SqlParameter("#Hosting_data_transfer", ddlhostingDataTrans.SelectedItem.ToString());
spa[23] = new SqlParameter("#Hosting_manage_dns_amt", txtHostingMangDnsAmt0.Text);
spa[24] = new SqlParameter("#Hosting_amt", txtHostingAmt0.Text);
spa[25] = new SqlParameter("#Hosting_c_ns1", txtHostingNS1.Text);
spa[26] = new SqlParameter("#Hosting_c_ns2", txtHostingNS2.Text);
spa[27] = new SqlParameter("#Hosting_c_ns3", txtHostingNS3.Text);
spa[28] = new SqlParameter("#Hosting_c_ns4", txtHostingNS4.Text);
int k = gs.Sp_InsertUpdateDelete("Sp_Hosting", spa);
if (k > 0)
{
Response.Write("<script>alert('Hosting Added Success');</script>");
}
Clear();
}
using(SqlConnection conn = new SqlConnection())
{
try
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction("Transaction1");
Cmd = new SqlCommand(sQuery, Conn);
Cmd.Transaction = tran;
//Your Code
tran.Commit(); //both are successful
}
catch(Exception ex)
{
//if error occurred, reverse all actions. By this, your data consistent and correct
tran.Rollback();
}
}
https://msdn.microsoft.com/en-us/library/a90c30fy.aspx
You need to modify your Stored procedure and use Transactions for this feature.
Something like this:
DECLARE #TranName VARCHAR(20);
SELECT #TranName = 'MyTransaction';
BEGIN TRANSACTION #TranName;
USE AdventureWorks2012;
DELETE FROM AdventureWorks2012.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION #TranName;
GO
MSDN Reference

Unable to add data in a datatable asp.net

DataRow new_row = tb11.NewRow();
for (i = 0; i < 8; i++)
{
new_row[i] = tb11.Rows[0][i].ToString();
}
tb11.Rows.Add(new_row);
I am running the following code to add data to a existing datatable but no data is inserted into the databale.
DataTable dt = ds3.Tables["FormName"];
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns[2].ColumnName = "EmpId";
dt.Columns[3].ColumnName = "EmpName";
dt.Columns[4].ColumnName = "Branch";
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["EmpId"] = UID;
dt.Rows[i]["EmpName"] = EmpName;
dt.Rows[i]["Branch"] = Zone;
}
dt.AcceptChanges();
foreach (DataRow row in dt.Rows)
{
string NEmpId = dt.Rows[j]["EmpId"].ToString();
string NEmpName = dt.Rows[j]["EmpName"].ToString();
}
you are calling newrow() on the same table tb11 from where you get your source data and adding new row in same table tb11. Also tb11.Rows[0] will access first row everytime

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

Dynamic parameter and query

I'm creating a search engine for my asp page.There are 15 pieces filtering options like Price,Date,Name etc.
Also,The use of Filtering Options is optional.If the filtering options are left blank,search will be made.
I found a solution by using if and string.
string sorgu = "";
dbcommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
if(UrunAdi.Text != string.Empty)
{
sorgu += "UrunAdi = #UrunAdi";
dbparameters prm = cmd.createparameter();
prm.Parametername = "#UrunAdi";
prm.Value = UrunAdi.Text;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;
it's running upper code without problem.However,I want to using a parameter to filter dynamic.
So,the user choose those categories through checkbox inside search engine.
When I try to run below code,I got the following error.
Must declare the scalar variable "#cat0".
Code:
string sorgu = "";
DbCommand cmd = CommandClassım.YeniCommand();
sorgu += "Select * From Urunler Where ";
DbParameter prm = cmd.CreateParameter;
for(int i = 0; i < Category.Length; i++)
{
sorgu += "Kategori = #cat" + i.ToString();
prm.ParameterName = "#cat" + i.ToString();
prm.Value = Category.Value;
prm.DbType = DbType.String;
cmd.Parameters.Add(prm);
}
cmd.CommandText = sorgu;
Just a hunch, but could it be that you're not providing the indexer for Category?
prm.Value = Category.Value;
I would think it should be:
prm.Value = Category[i].Value;

Regarding binding array to gridview

Hi
I have created session array :
int[] a = (int[])Session["values"];
Now i have to bind this value to my gridview. I have one column (boundfield in my gridview) in gridview.
I used code to bind array to gridview as follows, but its giving last value only as i want all the values to bind :
for (int i = 0; i < a.Length; i++)
{
str = "select * from Quest_Info where Quest_id='" + a[i] + "' order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();
}
Which code will work for this?
Asp.net, c#
Thank You.
Your code may not work because you are trying to bind gridview in the for loop which keep repeating and will result to bind only one last array id in the end.
You may try to prepare query out front before binding the gridview as example below.
string questIds = string.Empty;
for (int i = 0; i < a.Length; i++)
{
if (questIds.Length > 0)
questIds += ", ";
questIds += a[i];
}
string strSQL = "select * from Quest_Info where Quest_id IN ("+ questIds + ") order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();

Resources