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 :)
Related
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.
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;
}
Not sure if this question has been asked before, so here goes..
I have a front end app coded in C# windows forms. On a second form i have two datagridviews that gets populated from two different sql server pre-defined views
I need to refresh both datagrids at the same time with a single button click
My button click even looks like this..
private void RefreshBTN_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
How i understand this is, C# opens new connection, queries the DB and returns by filling datagridview1 with the required data. I would like the same click event to request data from another sql view and populate another datagridview at the same time. Visually both grids are aligned vertically on the same form, one on to of the other.
Many thanks in advance
Move the code for refreshing Grid1 into a separate function. Then copy paste and duplicate that function for Grid2. Change the SQL for Grid2 as well as the Grid2 name. Rename the copied function with 2. Then add a call to both functions so your button click will refresh both grids.
private void RefreshBTN_Click(object sender, EventArgs e)
{
//call both functions to refresh both on button click
RefreshGrid1();
RefreshGrid2();
}
private void RefreshGrid1()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//give this function a unique name to represent the second grid refresh
private void RefreshGrid2()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//rename this to your second grid name
dataGridView2.DataSource = dt;
}
i have a gridview where i have allowed paging.
but when i click second page the gridview disappears
here is the c# code :
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
OdbcDataAdapter adpState = new OdbcDataAdapter("SELECT CALL_NO,TDATE,
ID_NO,NAME,CONTACT,DEPARTMENT,ISSUE,STATUS FROM TBL_ITHELPDESK
WHERE (STATUS IS NULL OR STATUS <> 'CLOSED') AND TDATE= TO_DATE('" +
txtDate.Text.ToString().Trim() + "','MM-DD-YYYY')", con1);
DataSet ds = new DataSet();
adpState.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
can anyone help to find where i'm going wrong
You have to check multiple things.
Check the query with the one that is working, Is it Same?
Check the con1 variable is defined outside of any other method.
Define con1 in a class not in a method, something like that
odbcConnection con = new odbcConnection(ConectionString);
con.Open();
string str = DropDownList1.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(#"
select distinct
a.DepotCode, a.CustWt, b.CustName,
b.Lat_Degree, b.Lat_Minute, b.Lat_Second,
b.Lon_Degree, b.Lon_Minute, b.Lon_Second
from tblDepotCustMapping a, tblCustomers b
where DepotCode='" + str + "' and a.CustCode=b.CustCode", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
I want to use this gridview value to calculate.. how to access the values in the grid.. help me..
There are many ways in your scenario but the simple answer is to loop on the datatable in your dataset (ds) after binding to GridView1 and then bind that table to other gridview
It will be easier to access the values through the underlying DataSet rather than through the GridView. IE:
con.Open();
string str = DropDownList1.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter("select distinct a.DepotCode,a.CustWt, b.CustName,b.Lat_Degree,b.Lat_Minute,b.Lat_Second,b.Lon_Degree,b.Lon_Minute,b.Lon_Second from tblDepotCustMapping a, tblCustomers b where DepotCode='" + str + "'and a.CustCode=b.CustCode", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
You can access the actual data using the DataSet variable ds.
Then something like:
DataTable t = ds.Tables[0];
// Manipulate and calculate your data here. IE:
foreach(DataRow row in t.Rows)
{
row["column_name"] = 'some calculated value or your manipulated value here';
}
It's easier to do the calculations with the data in the DataSet itself before you bind it to the GridView.
However, if you want to access the items in the grid you can use gridview RowDataBound event to do certain things after the server controls bind to the datasource.
If you have this GridView in your page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"
OnRowDataBound="GridView1_RowDataBound" />
You can put the event handler in your code-behind file. A GridViewRowEventArgs object is passed to the event-handling method, which allows you to access the properties of the row that raised the event.
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Access and modify the cells of your GridView.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
// Retrieve the underlying data item.
DataRowView rowView = (DataRowView)e.Row.DataItem;
// Retrieve the DepotCode value for the current row.
String depot = rowView["DepotCode"].ToString();
}
}
See also: GridView.RowDataBound Event documentation on MSDN.