In my aspx page I have a DetailsView and a SqlDataSource and a button labeled "Next".
The datasource mode has been set to DataReader since i only need to advance forward.
In my cs page, I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("PickRandomQuestions", conn);
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.Add("QuizID", SqlDbType.Int);
comm.Parameters["QuizID"].Value = 1;
conn.Open();
reader = comm.ExecuteReader();
QuestionDetails.DataSource = reader;
QuestionDetails.DataBind();
}
}
protected void ButtonNext_Click(object sender, EventArgs e)
{
if (reader.Read())
{
QuestionDetails.DataSource = reader;
QuestionDetails.DataBind();
}
else
{
conn.Close();
reader.Close();
}
}
Now when i click on the Next button, i get System.NullReferenceException: Object reference not set to an instance of an object.
What am i doing wrong?
Related
I have to automatically reload the gridview which contains the list of the brand names. What should be done to automatically reload the data gridview when the "Brand has been added" meessage is shown.I have the data gridview in another form.
public partial class AddBrand : Form
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
public AddBrand()
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
}
private void Clear()
{
btnSave.Enabled = true;
btnUpdate.Enabled = false;
tbBrand.Clear();
tbBrand.Focus();
}
private void BtnSave_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you want to save this brand?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
cn.Open();
cm = new SqlCommand("INSERT INTO tblBrand(brand)VALUES(#brand)", cn);
cm.Parameters.AddWithValue("#brand", tbBrand.Text);
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Brand has been added.");
Clear();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
Brand brand = new Brand();
brand.ShowDialog();
}
}
This is the design:
Hope as per your code Brand is the form showing GridView. In this form you can open the form AddBrand.
var addBrand = new AddBrand();
var result = addBrand.ShowDialog();
if(result == DialogResult.Yes)
ReloadLogic()// you can read from db
In BtnSave_Click event in Brand form you can write
this.DialogResult = DialogResult.Yes; Close();
If you want to reload the datagridview when the "Brand has been added" meessage is shown, you can read data to datagridview again.
You can refer to the following code in the form containing datagridview:
private void Form1_Load(object sender, System.EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
cn = new SqlConnection(dbcon.MyConnection());
cn.open();
string sql = "select * from tblBrand";
SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
cn.close();
}
I'm having a problem with redirecting the page to the another one according to the selectedvalue from dropdownlist.
I can list categories in the dropdownlist using SQL Server.
namespace Deneme
{
public class Baglanti
{
public SqlConnection Baglanma()
{
//integrated security windows auth için.
SqlConnection baglan = new SqlConnection("Server=DESKTOP-IB3QGLL;Database=Sports;Integrated Security = True");
baglan.Open();
SqlConnection.ClearPool(baglan);
SqlConnection.ClearAllPools();
return (baglan);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand komut2 = new SqlCommand("SELECT clubid,club_name FROM kulupler", baglan.Baglanma());
SqlDataReader reader = komut2.ExecuteReader();
baglan.Baglanma();
DDLProduct.DataSource = reader;
DDLProduct.DataValueField = "clubid";
DDLProduct.DataTextField = "club_name";
DDLProduct.DataBind();
}
protected void BtnGonder_Click(object sender, EventArgs e)
{
Response.Redirect("Category.aspx?ID="+DDLProduct.SelectedValue);
}
Product:
<asp:DropDownList ID="DDLProduct" runat="server">
</asp:DropDownList>
<asp:button id="BtnGonder" runat="server" text="Gönder" OnClick="BtnGonder_Click">
</asp:button>
I can list all the categories in the dropdown list. When I click the button it's always goes to Category.aspx?ID=1 which is the value of the first element of the dropdownlist.
try this
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtblItemList = new DataTable();
using (SqlConnection conn = DataExecutor.GetSqlConnection()){
conn.Open();
SqlCommand komut2 = new SqlCommand("SELECT clubid,club_name FROM
kulupler", conn);
//SqlDataReader reader = komut2.ExecuteReader();
using(SqlDataReader reader = DataExecutor.GetSqlDataReader(komut2,
CommandBehavior.Default))
{
dtblItemList.Load(reader);
}
}
DDLProduct.DataSource = dtblItemList;
DDLProduct.DataValueField = "clubid";
DDLProduct.DataTextField = "club_name";
DDLProduct.DataBind();
}
I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}
I am devleoping a online airline reservation system in which i have two dropdownlists to select source and destinations and a label .this label will show " there are no flights" if there are no matching routes retrieved from the database (in this case its sqlserver 2008).i have written the following code which tries to do so, but when i postback or refresh the page the label with " there are no flights" is till visible.what is wrong with my code please anyone help me with that.
public partial class Dropdndemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
//string Sqlcmnd="select Source from Ars2.1.2.dbo.Scheduling";
con.Open();
if (!Page.IsPostBack)
{
SqlCommand com = new SqlCommand("select distinct Source from Schedulings", con);
SqlCommand comn=new SqlCommand("select distinct Destination from Schedulings", con);
//SqlDataReader readr;
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "Source";
// DropDownList1.DataTextField = "Destination";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "select Source");
con.Close();
con.Open();
DropDownList2.DataSource = comn.ExecuteReader();
DropDownList2.DataTextField = "Destination";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "select Destination");
con.Close();
}
//con.Close();
// DropDownList1.DataBind();
//con.Close();
if (IsPostBack)
Label3.Text = "";
//Label1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// string Source = DropDownList1.SelectedValue.ToString();
// Label1.Text = Source;
}
protected void Button1_Click(object sender, EventArgs e)
{
string src = DropDownList1.SelectedItem.ToString();
string desti = DropDownList2.SelectedItem.ToString();
if ((src == desti) && IsPostBack)
{
Label1.Text = "Source And Destination cant be same!";
}
SqlConnection lop = new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
lop.Open();
SqlCommand cmd = new SqlCommand("select * from Schedulings where Source=#Source and Destination=#Destination", lop);
cmd.Parameters.AddWithValue("Source", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("Destination", DropDownList2.SelectedItem.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
Label3.Text = "No planes available in this route!!!";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
I suppose you are refreshing page using F5 or by right clicking on page and opting refresh option or using refresh button of browser. If this is the case then I am scared it's not refresh, it's repeating previous action. That means if you were searching for flight and refreshing using above options, it will again search for flight using same search criteria. You can confirm it by putting debugger on search event. You can avoid this behavior by setting and clearing Session or ViewState and manage label text using it.
I am using c# and asp.net in my project.I wanted to get the selectedindex of the dropdownlist but I am getting always as 0.Here is my code of binding the dropdown list with data
MySqlDataReader dr = null;
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select category from lk_category";
MySqlCommand command = mycon.CreateCommand();
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataValueField = "category";
DropDownList1.DataBind();
dr.Close();
str = "select technology from lk_technology";
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList2.DataSource = dr;
DropDownList2.DataValueField = "technology";
DropDownList2.DataBind();
}
catch (Exception ex) { Response.Write("Exception reding data" + ex); }
finally
{
//dr.Close();
mycon.Close();
}
And I am trying to get selected index by:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
catID = DropDownList1.SelectedIndex+1;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
techID = DropDownList2.SelectedIndex;
}
Here is my page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valid"] == null)
Response.Redirect("admin.aspx");
panel1();///If session valid then show panel1;
}
Please tell me where I am going wrong.
That is because you refill the drop down list in page load without checking that it is not post back.
Warping your try-catch (drop down fill) code with
if (!this.IsPostBack)
{
...
}
should solve the problem.