data grid view no affected rows - c#

I want to fill datagridview when rows affected=< 0 but i get error in line 47 gridview (id) = "correctgridview" runat = "server"
the first case work well but the error in the datagridview
mycode
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void insertButton_Click(object sender, EventArgs e)
{
int rowsaffected = 0;
dataset ds = new dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=attend; Integrated Security=true;");
SqlCommand cmd;
cn.Open();
cmd = new SqlCommand("atten", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "#myid";
param.Value = idTextBox.Text;
cmd.Parameters.Add(param);
rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected > 0)
{
resultLabel.Text = "added successful";
}
else
{
resultLabel.Text = "attend error";
SqlCommand command;
command = new SqlCommand("select id, courses.course , course_date , st_lec , location from courses inner join regestration on courses.course = regestration.course where id = 2", cn);
SqlDataAdapter adapte = new SqlDataAdapter(command);
DataTable Dt = new DataTable();
adapte.Fill(Dt);
correctGridView.DataSource = Dt;
correctGridView.DataBind();
}
cn.Close();
}
}

Related

insert data into drisview and display in same gridview

This is neither producing an error nor output. Help me out in this. Here my code is :
public partial class ScoHelpDesk : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
SqlDataAdapter adapt;
DataTable dt;
SqlConnection con2, con3;
SqlCommand cmd, cmd1, cmd2;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData_Sheet();
}
}
protected void InsertData1(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlserver"].ConnectionString);
TextBox t1 = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
TextBox t2 = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
TextBox t3 = (TextBox)GridView1.FooterRow.FindControl("TextBox6");
TextBox t4 = (TextBox)GridView1.FooterRow.FindControl("TextBox8");
TextBox t5 = (TextBox)GridView1.FooterRow.FindControl("TextBox10");
TextBox t6 = (TextBox)GridView1.FooterRow.FindControl("TextBox12");
cmd = new SqlCommand("insert into tblHelpDesk (Name,Purpose,ContactNo,AlternativeNo,Email,Address) values(#Name,#Purpose,#ContactNo,#AlternativeNo,#Email,#Address)", con);
con.Open();
cmd.Parameters.AddWithValue("#Name", t1.Text);
cmd.Parameters.AddWithValue("#Purpose", t2.Text);
cmd.Parameters.AddWithValue("#ContactNo", t3.Text);
cmd.Parameters.AddWithValue("#AlternativeNo", t4.Text);
cmd.Parameters.AddWithValue("#Email", t5.Text);
cmd.Parameters.AddWithValue("#Address", t6.Text);
cmd.ExecuteNonQuery();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
catch (Exception ex)
{ }
}
private void BindData_Sheet()
{
DataTable dt = new DataTable();
using (SqlConnection con2 = new SqlConnection(con.ConnectionString))
{
string strQuery = "SELECT * FROM tblHelpDesk ";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}

GridView Not showing when i delete the all rows from database table

i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx

What is the way to populate a dropdownlist from a database in asp.net by using classes?

I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}

facing an error with registration btn

When I fill the registration form and click on the button to move to user panel it does not move to the user panel, it freezes on the registration. In the user panel code behind it shows this message:
Object reference not set to an instance of an object.
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email,Country, State,City, Post, Img, Logo,RegDate) VALUES (#UID,#FN,#LN,#Password,#RePass,#Email,#Country,#State,#City,#Post,#Img,#Logo,#RegDate)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#UID", UsrNme.Text);
cmd.Parameters.AddWithValue("#FN", fnbox.Text);
cmd.Parameters.AddWithValue("#LN", lnamebox.Text);
cmd.Parameters.AddWithValue("#Password", passtxtbx1.Text);
cmd.Parameters.AddWithValue("#RePass", passtxtbx2.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Post", postbox.Text);
cmd.Parameters.AddWithValue("#Img", persimgFileUpload1.FileName);
cmd.Parameters.AddWithValue("#Logo", logoFileUpload.FileName);
//Get the Current Date Time here
cmd.Parameters.AddWithValue("#RegDate", DateTime.Now);
if (!string.IsNullOrEmpty(UsrNme.Text))
{
Lblcheckusername.Text = "User Name Already Exist";
Lblcheckusername.ForeColor = System.Drawing.Color.Red;
}
else
{
Lblcheckusername.Text = "User Name Available";
Lblcheckusername.ForeColor = System.Drawing.Color.Green;
}
if (persimgFileUpload1.HasFile)
{
persimgFileUpload1.SaveAs(Server.MapPath("~/images/users/" + persimgFileUpload1.FileName));
}
if (logoFileUpload.HasFile)
{
logoFileUpload.SaveAs(Server.MapPath("~/images/Logos/" + logoFileUpload.FileName));
}
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
Here is the user panel codebehind where the error appears on the first code line:
USRNMElbl.Text = Session["UsrNme"].ToString();
if (Session["UsrNme"] != null)
{
}
if (!Page.IsPostBack)
{
DataTable countrycascd = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [countryID],[country] FROM [countr]", con);
adaptar.Fill(countrycascd);
countrdrdolst.DataSource = countrycascd;
countrdrdolst.DataTextField = "country";
countrdrdolst.DataValueField = "countryID";
countrdrdolst.DataBind();
}
countrdrdolst.Items.Insert(0, new ListItem("Välj land", "0"));
}
if (!Page.IsPostBack)
{
DataTable Sectiondt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [CateID],[Category] FROM [Section]", con);
adaptar.Fill(Sectiondt);
Catedrdoads.DataSource = Sectiondt;
Catedrdoads.DataTextField = "Category";
Catedrdoads.DataValueField = "CateID";
Catedrdoads.DataBind();
}
Catedrdoads.Items.Insert(0, new ListItem("Select Section", "0"));
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 2;
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void addadsbtn_Click(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO [ads] ([Section], [Category], [UID], [AdsTit], [AdsDesc], [Country], [State], [City], [AdsPrice], [Img1], [img2], [img3], [img4], [img5], [Wtags]) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State, #City, #AdsPrice, #Img1, #img2, #img3, #img4, #img5, #Wtags)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#Section", Catedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Category", SubCatedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#UID", USRNMElbl.Text);
cmd.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
//cmd.Parameters.AddWithValue("#AdsDesc", Editor1.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
cmd.Parameters.AddWithValue("#Img1", FileUpload1.FileName);
cmd.Parameters.AddWithValue("#Img2", FileUploadImg2.FileName);
cmd.Parameters.AddWithValue("#Img3", FileUploadImg3.FileName);
cmd.Parameters.AddWithValue("#Img4", FileUploadImg4.FileName);
cmd.Parameters.AddWithValue("#Img5", FileUploadImg5.FileName);
cmd.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
The problem might be your Session["UsrNme"] is null
if (Session["UsrNme"] != null)
{
USRNMElbl.Text = Session["UsrNme"].ToString();
}
else
{
return;
}
You could also read http://www.codingdefined.com/2014/06/object-reference-not-set.html

DropDownList Value won't change

When I select any value from the DropDownList, the first one gets selected.
The code's purpose is whenever I choose a value from the DropDownList the corresponding value from the database should be displayed in the TextBox.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable dt = new DataTable();
SqlCommand sqlCmd = new SqlCommand("SELECT SeminarNameE,TrainerName FROM SeminarData WHERE SeminarName='" + DropDownList1.SelectedItem.Value +"'", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
TextBox1.Text = dt.Rows[0]["SeminarNameE"].ToString();
TextBox2.Text = dt.Rows[0]["TrainerName"].ToString();
}
}
Replace your page load with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
}
It needs !Page.IsPostBack, because everytime you bind, you clear any selections. In this code, it binds on every page load. Adding !Page.IsPostback will ensure it binds only the first load.

Categories

Resources