ASP.NET DropDownList Issue - c#

[...]
public DataSet ReturnPromoMagazinesDs()
{
MySql.Data.MySqlClient.MySqlConnection mysqlConnection = new MySql.Data.MySqlClient.MySqlConnection(this.connectionString);
MySql.Data.MySqlClient.MySqlCommand mysqlCommand = new MySql.Data.MySqlClient.MySqlCommand("SELECT id, magazine_name FROM `magazines`", mysqlConnection);
MySql.Data.MySqlClient.MySqlDataAdapter mysqlAdaptor = new MySql.Data.MySqlClient.MySqlDataAdapter(mysqlCommand);
DataSet ds = new DataSet();
mysqlAdaptor.Fill(ds, "magazines");
return ds;
}
[...]
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = coreObject.ReturnPromoMagazinesDs();
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = ds.Tables["magazines"].Columns["magazine_name"].ColumnName;
DropDownList1.DataValueField = ds.Tables["magazines"].Columns["id"].ColumnName;
DropDownList1.DataBind();
}
[...]
<asp:dropdownlist id="DropDownList1" runat="server"></asp:dropdownlist>
The above code works ok, untill I'm fetching the DropDownList1.SelectedValue which is always 1 (the fist value from the table). Values in the table aren't the blame for this, and if I manually add items to the DropDownList, everything works fine. What can cause this?

Does it work properly when you wrap all of the code in the Page_Load method in the following:
if (!IsPostBack) { /* Code as in the original post */ }

Not sure if something is getting lost in transalation but you could simplify the following lines, even if its doesnt fix the issue.
DropDownList1.DataTextField = "magazine_name";
DropDownList1.DataValueField = "id";

Related

GridView not appearing on webpage

I am building a web form. I have one search field and a search button. I am connecting to MS Access database to retrieve and display the result on the grid view. But my grid view is not appearing on the web page.
Can anyone please help me to find out where I am wrong?
Here is my aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Smita\\Desktop\\Project.accdb");
DataTable dt = new DataTable() ;
if (txtMerchant.Text.Length > 0)
{
con.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand("select * from Test where Merchant ID like '" + txtMerchant.Text + "%'", con);
DBAdapter.Fill(dt);
GridView1.DataSource = dt;
}
You have to call the DataBind, binding method first after you assign the data source.
Like that:
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataSource = dt; //Assigned a blank table.
"dt" Doesn't seem to point to anything.

c# asp.net Index was out of range. when I trying to select a row

I have a gridview on my page. And I have 2 snippets of SQL code to binds that gridview.
First one is run on page load. If there are records returned from the first SQL, I can select a row on gridview.
But the problem is when there is no record returned from the first SQL, I have button that runs another SQL and binds its result to the gridview too. But when I try to select a row, I get this error:
Index was out of range. when I trying to select a row Must be non-negative and less than the size of the collection. Parameter name: index
My code is like that
First SQL (its run on page load)
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and thats the second SQL that when runs when I click button
void listelehepsi()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and this is the GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int secili;
secili = GridView1.SelectedIndex;
GridViewRow row = GridView1.Rows[secili]; // I GOT ERROR HERE
TextBox1.Text = row.Cells[1].Text;
}
why Am I getting this error ?
EDIT--
I got solve changing the page load sql like this;
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
if (!IsPostBack)
{
GridView1.DataBind();
}
else
{
//
}
baglanti.Close();
}
Make sure that you are not rebinding your datagrid on postback - you can do this in your PageLoad event - something like
if (!IsPostback)
{
... bind your datagrid
}
In the GridView1_SelectedIndexChanged event, could you simply do a RowCount to see if the value is != 0 before the other code runs?
if (GridView1.RowCount <= 0)
{
return;
}

Gridview display

I dont know what it is but i'm having all sorts of issues with this gridview. Below is the code but the issues is the grid is not displaying. Visibility is set to true and the query does return results. So I'm asking for another set of eyes to point out what went wrong here.
Thank you
protected void btnDisplay_Click(object sender, EventArgs e)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\levels.mdb";
DataSet ds;
using (OleDbConnection myConnString = new OleDbConnection())
{
myConnString.ConnectionString = connString;
using (OleDbCommand selectCommand = new OleDbCommand())
{
selectCommand.CommandText = "select * from tblTest";
selectCommand.Connection = myConnString;
myConnString.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = selectCommand;
ds = new DataSet();
da.Fill(ds, "test");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}//end click event
and the gridview
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
or
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
data source should have been:
GridView1.DataSource = ds.Tables["test"];
GridView1.DataBind();

How to select data from table selected in dropdownlist?

I have a dropdownlist on a page and in a dropdownlist I have names of the tables in database.
I don't know how to insert data from the selected table in the gridview or datalist.
I tried with using the code from another c# project I did in school, but it didn't work
edit: answer added here
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter da = new OleDbDataAdapter (string.Format("SELECT * from {0}", dropDownList.SelectedValue), con);
DataSet ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
You can tell the code to put the dropdowlists selected item's value in the query as follows:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con= new OleDbConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT * FROM {0}",DropDownList1.SelectedValue), con);
DataSet ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
I've tested this before posting it and it works on my machine. When you so if you can not get it worked the problem should be somewhere else.
That is very easy to do. I assume your dropdownlist is in your gridview which is also a asp gridview. If this is the case then in the event you have catching the selectedindexchange or by button click. You will have to find the dropdown in the gridview and then use the selectedvalue property. It will look like this to find it(place this in your event handler)
Dim ddl as dropdownlist = gridview.row(e.rowindex).findcontrol("dropdownID")
Dim val = ddl.selectedvalue
The only changes that might have to be made in regards to finding the control is depending on what rowtype the dropdown is in and also the event being used. If the above wont find the control you can try gridview.row.findcontrol("dropdownID")
Once you get the value, you can call the method for the insert and pass it as a parameter :)

create a dropdown list in c# .net server side

I trie to create a dropdown list in c# .net server side ... but this is not working .. anyone know what is it going wrong here?
string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
while (msDataReader.Read())
{
dropDown.DataSource = msDataReader["Name"].ToString();
dropDown.DataTextField = msDataReader["Name"].ToString();
dropDown.DataValueField = msDataReader["EventTypeID"].ToString();
dropDown.DataBind();
}
string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";
dropDown.DataBind();
msSQLConnectoin.Close();
msSQLConnectoin.Dispose();
dropDown.Items.Insert(0, "--Select Name--");
}
Replace msDataReader["Name"].ToString() with your data reader name msDataReader
Sample Code:
protected void Page_Load(object sender, EventArgs e)
{
bindDropdownlist()
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select colmn1,colmn2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "colmn1";
DropDownList1.DataValueField = "colmn2";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..select...");
}
I believe the DataTextField and DataValueField should be string representations of the property you've bound, see this related post:
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";
Read here
The DataSource property is supposed to be set with an object containing all the informations the control needs to be bound to. The DataTextField and the DataValueField should be a reference to actual data on the DataSource object. A simple way to achieve your goal could be to prepare a DataTable using Text and Value fields and then bind the control this way:
dropDown.DataSource = dt;
dropDown.DataTextField = "Text";
dropDown.DataValueField = "Value";
dropDown.DataBind();
Here on the msdn web site you'll find your same scenario.

Categories