Read custom row, datareader (C#) - sqldatareader

this code adds only the first line, how do I add the second line of the column "mail"
var cs = ConfigurationManager.ConnectionStrings["ConnectionString"];
var sc = new SqlConnection(cs.ConnectionString);
sc.Open();
string str = "Select * From [Table1]";
var cmd = new SqlCommand(str, sc);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ListBox1.Items.Add(dr["mail"].ToString());
}
sc.Close();

if (dr.HasRows)
{
while (dr.Read())
{
/* your code */
}
}
else
{
/* error message */
}

Related

Using sqldatareader in another sqldatareader

I'm checking table to see if ID exists in table A if that ID exists insert it in table B but I also would like to check in table B if that ID number was not already inserted. But my issue is that I'm not able to combine all of that together. I'm not sure how to put a sqldatareader into another.
SqlCommand cmd1 = new SqlCommand("CreateID", con);
SqlCommand cmd = new SqlCommand("selectID", conn);
SqlCommand com = new SqlCommand("SelectIDfromtableB", con);
public SqlDataReader dr;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
sessionCount++;
Session["Count"] = sessionCount;
cmd1.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
}
reader.Close();
cmd1.ExecuteNonQuery();
}
else
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert( Id number does not exist'); window.location.href = 'Return.aspx';", true);
}
}
if (dr.Read())
{
lblError.Text = "Data was inserted before";
}
dr.Close();
You can minimize the code, use one connection for all the readers and one command, but you have to set the CommandText each time and clear the parameters if there were any. Use the using keyword to make sure your resources are disposed.
If there is anything you need to check in your first command, you can set a flag
using (var conn = GetTheConnection())
{
conn.Open();
//flag to check if id exists
var idExists = false;
var cmd= new SqlCommand("CreateID", conn );
cmd.Parameters.Add("#crate_box_no", SqlDbType.NVarChar).Value = id;
using (var myReader = cmd.ExecuteReader())
{
if(myReader.Read())
{
idExists = true;
}
}
//clear parameters
if (idExists)
{
cmd.Parameters.Clear();
cmd.commandText = "You 2nd SQL Script here"
using (var myReader = cmd.ExecuteReader())
{
}
}
}
Cant you just do 2 queries? First one counting rows of id occurences, if greater 0 then count occurences in table b, if 0 continue?
Edit Example pseudo code:
command1 = "select id from tableA where id = toLookForId";
Define GridView1 and Gridview2;
Gridview1.datasource = sqldatareader.executenonquery(command1);
Gridview1.databind();
if gridview1.rows.count > 0 then
command2 = "select id from tableB where id = toLookForId";
Gridview2.datasource = sqlreader.executenonquery(command2);
gridview2.databind();
if gridview2.rows.count = 0 then
//your code goes here
else
//id exists so quit
return;
end if
end if
Regards,
Maheshvara

set list of object as dropdown list datasource

I have this method: that returns a list of Category object , and i want to set this list output as Drop down list Datasource in c# , how can i do that
public List<Category> GetAllCategories()
{
SqlConnection con = new SqlConnection(connectonstring);
SqlCommand cmd = new SqlCommand("GetAllCategories", con);
cmd.CommandType = CommandType.StoredProcedure;
List<Category> Categories = new List<Category>();
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Category cat = new Category();
cat.JobCategoryid = Convert.ToInt32(reader["JobCategoryid"]);
cat.CategoryName = reader["categoryName"].ToString();
Categories.Add(cat);
}
reader.Close();
return Categories;
}
catch (SqlException err)
{
return null;
}
finally
{
con.Close();
}
}
Like this:
dropdownList.DataSource = GetAllCategories();
dropdownList.DateTextField= "CategoryName";
dropdownList.DataValueField = "JobCategoryid";
dropdownList.DataBind();

where to check the state of dynamically created checkboxes

Hello in my programme I need to create dynamically checkboxlist with items - got from teh database.
The problem is when Clicking a button i should get the text from cn only checked checkboxes and I should redirect the user to another page
And I have difficulty with determining width of the controls are checkedore
if I checked immediately after they are added
So if I write
if (mycheckbox.Items[s].Selected==true)
after this line
Page.FindControl("form1").Controls.Add(mycheckbox);
they are not checked still so this will be always false)
On postback event (clicking the button ) - we know on postback event dynamic controls no longer exist)
here is my code
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
}//End of try
catch (Exception ex)
{ }
}//end of for
I've implemented a client-side check using jQuery in my online Quiz engine (demo: http://webinfocentral.com): the extract from that code snippet follows:
var _rows = $(this).find('tr');
for (i = 0; i < _rows.length; i++) {
// find out if checkbox is checked
_checked = $(_rows[i]).find('input:checkbox').is(':checked');
}
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
mycheckboxList = new CheckBoxList();
mycheckboxList.ID = "chkblextracharge" + i.ToString();
while (rd.Read())
{
ListItem LI = new ListItem(rd["Extra_Charge_Description"].ToString(), s.ToString());
LI.Selected = rd["Selected_Criteria"] == "TRUE";
mycheckboxList.Items.Add(LI);
s++;
}
Page.FindControl("form1").Controls.Add(mycheckboxList);

ASP.NET C# - Redirect After Inserted Record

I perform and insert new record, this code below works for for inserting. After that, I want to redirect to another page using window.parent.location with the ID (ProposalID) that I used in the insert.
private void ExecuteInsert(string ProposedID, string CreatedBy, string Note)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO MDF_ProposedNote (ProposedID, Note, CreatedBy)
VALUES "
+ " (#ProposedID, #Note, #CreatedBy)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ProposedID", SqlDbType.Int, 10);
param[1] = new SqlParameter("#Note", SqlDbType.VarChar, 2000);
param[2] = new SqlParameter("#CreatedBy", SqlDbType.Int, 10);
param[0].Value = ProposedID;
param[1].Value = Note;
param[2].Value = CreatedBy;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
}
}
This is where I and to redirect to another page + RecordID
Response.Write("<script>window.parent.location =
'ProposalItemView.aspx?ProposedID='"<%=ProposedID%>";</script>");
Please help. Thanks in advance.
You probably want
Response.Redirect(string.format("~/ProposalItemView.aspx?ProposedID={0}", ProposedID), true);

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

Resources