In gridview is not displaying the first row - c#

In gridview that am try to displaying the data in the database but it is ignoring the first row from the tabel & taking the rest of row.., plz suggest me what to do..
below is my code.
protected void Page_Load(object sender, EventArgs e)
{
DBLibrary obj = new DBLibrary();
String Parent = (string)Session["parentName"];
String ss = "Select StudentId from Tbl_Parents where parentName='" + Parent + "'";
SqlDataReader dr6 = obj.ExecuteReader(ss);
dr6.Read();
string id = dr6[0].ToString();
string bind = "SELECT AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.StudentId ='" + id + "')";//and (AnuFeeMaster.ChkDate='" + date.ToString() + "') ";
SqlDataReader dr = obj.ExecuteReader(bind);
dr.Read();
gv1.DataSource = dr;
gv1.DataBind();
}

Remove the dr.Read(); line.
You are passing the reader already advanced with one position.

Related

How to search over whole cities in combobox

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);
If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}

Need to find ID number from database using string in c#

I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";

Setting a button on Gridview row, conditionally

I have a button on my Gridview:
<asp:Button ID="lnk_ship" runat="server" CssClass="btn-mini" Text="Ship Software" />
I am loading my Gridview from SQL, to a Class, then a DataBind() event,
protected void FilterResults(object sender, EventArgs e)
{
var shipments = new List<SoftShipments>();
DateTime dt1 = Convert.ToDateTime(Textbox1.Text);
DateTime dt2 = Convert.ToDateTime(Textbox2.Text);
string cvt1 = "'" + dt1.Year.ToString() + "-" + dt1.Month.ToString() + "-" + dt1.Day.ToString() + "'";
string cvt2 = "'" + dt2.Year.ToString() + "-" + dt2.Month.ToString() + "-" + dt2.Day.ToString() + "'";
string qry = null;
if (Showshipped.Checked)
{
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2;
}
else {
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2 + " and sft_shipped = 'No'";
}
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("softship"));
conn.Open();
SqlCommand cmd = new SqlCommand(qry, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
shipments.Add(new SoftShipments() { index = (int) dr["id"], softtitle = dr["sft_SoftTitle"].ToString(),
productID = dr["sft_ProductID"].ToString(), ver = dr["sft_Version"].ToString(),
custnam = dr["sft_CustName"].ToString(), title = dr["sft_Title"].ToString(),
comp = dr["sft_Company"].ToString(), shipAddr = dr["sft_ShipAddress"].ToString(),
dept = dr["sft_Dept"].ToString(), city = dr["sft_City"].ToString(), state = dr["sft_State"]
.ToString(), postalCd = dr["sft_PostalCd"].ToString(), country = dr["sft_Country"].ToString(),
email = dr["sft_Email"].ToString(), entry_date = dr["sft_Entry_Dt"].ToString(),
ship_date = dr["sft_Ship_Dt"].ToString(), shipped = dr["sft_Shipped"].ToString()
});
}
gdv_Ship.DataSource = shipments;
gdv_Ship.DataBind();
conn.Close();
}
I would like to load the Gridview with the button visible if the value "shipped = 'No' or not visible if 'Yes' ... just not quite certain where to add this code? Any assistance would be appreciated.
Regards,
You could subscribe to the databound event of the grid, and then show/hide the buttons in the template with a FindControl("controlName")

How to not catch the old data in page load

I trying to update my profile but it keep catching the old data when it update. What can be done to solve this problem. Please help me out on this problem thanks!
protected void Page_Load(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
con.Open();
SqlCommand cm = new SqlCommand("Select * from MemberAccount where nric = '" + nric + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["address"].ToString();
txtContact.Text = dr["contact"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
if (txtContact.Text.Equals("") || txtEmail.Text.Equals(""))
{
lblMessage.Text = "Do not leave blank fill to update your profile!";
}
else
{
string strQuery = "Update MemberAccount Set address = '" + txtAddress.Text + "', contact = '" + txtContact.Text + "', email = '" + txtEmail.Text + "' Where nric = '" + nric + "'";
SqlCommand cmd = new SqlCommand(strQuery);
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Profile Updated.";
}
}
Sounds like you could just apply an IsPostBack check in your Page_Load method. http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// Load data
}
}
Note: your code looks susceptible to SQL injection.

Using SQL Between Query and Showing all results in ASP.NET C#

this is my sample code to check the data on Table1 using 2 filters, column1 and between data in column2. The code I have is working but is only getting 1 result. So for example. I enter "1" in textbox1, "3" in textbox2 and "6" in textbox3. Select * from TABLE1 where COLUMN1 = '1' AND COLUMN2 BETWEEN '3' AND '6' -- when run in sql result is 3,4,5,6 but in C# I am only getting "6". Can you help me with this to get "3,4,5,6" as a result. Thank you.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection SC;
SqlCommand CMD;
SqlDataReader DR;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DR = CMD.ExecuteReader();
if (DR.HasRows)
{
while (DR.Read())
{
label1.Text = DR["COLUMN2"].ToString();
}
}
}
}
}
Your loop is not appending the values, rather overwriting Label1. Change your while loop to
while (DR.Read())
{
label1.Text += DR["COLUMN2"].ToString() + ",";
}
if (label1.Text.EndsWith(",")) label1.Text = label1.Text.SubString(0, label1.Text.Length-1) //Remove the last comma
Change
label1.Text = DR["COLUMN2"].ToString();
as
label1.Text = label1.Text +", " + DR["COLUMN2"].ToString();
if (Label1.Text.Length > 2)
Label1.Text = Label1.Text.Substring(2);
try this code
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(CMD);
da.Fill(ds);
string data="";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++ )
{
if(data=="")
{
label1.Text = ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
else
{
label1.Text +=","+ ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
}
There are a number of methods to combine results into a comma-separated list. However, using string concatenation should not be one - concatenating strings is slow, especially if you might have a large number of results. Try one of the following instead:
Using a StringBuilder
StringBuilder sb = new StringBuilder();
boolean doneFirstRow = false;
while (DR.READ())
{
if (doneFirstRow)
{
sb.Append(", ");
}
else
{
doneFirstRow = true;
}
sb.Append(dr["COLUMN2"].ToString());
}
Label1.Text = sb.ToString();
Using a List with String.Join:
List<string> values = new List<string>();
while (DR.READ())
{
values.Add(dr["COLUMN2"].ToString());
}
Label1.Text = String.Join(", ", values);
NB: If not using NET4.5 you'll need String.Join(", ", values.ToArray())

Categories

Resources