I am having difficulty in displaying the dynamic data into text-boxes. I am in a situation where I have multiple text-boxes and I want to fetch value from table where column name is 'registration_charges' and 'amount'. Now column registration_charges' contains data e.g., 'OPD_CHARGES', 'DR.Charges' and 'amount' column has data e.g.,:- 5000, 1000. I want to display amount in text box accordingly.
<asp:Label runat="server" >OPD Ch.</asp:Label>
<asp:TextBox ID="txtopd_charges" runat="server" Width="100px"
style="text-
align: right;float:right;margin-right:15px;">/-</asp:TextBox>
<asp:Label runat="server" >DR Ch.</asp:Label>
<asp:TextBox ID="txtdr_charges" runat="server" Width="100px"
style="text-
align: right;float:right;margin-right:15px;">/-</asp:TextBox>
Back-end code:
//connection code
con.Open();
SqlCommand cmd = new SqlCommand("SELECT amount FROM
Mst_Charges WHERE registration_charges IN('OPD_CHARGES',
DR.Charges')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
txtopd_charges.Text = ???
txtdr_charges.Text = ???
}
else
{
}
}
catch (Exception ex)
{
}
}
In your query you must select registration_charges along with the amount
SqlCommand cmd = new SqlCommand("SELECT amount,registration_charges FROM
Mst_Charges WHERE registration_charges IN('OPD_CHARGES',
DR.Charges')", con);
You can fetch data of your DataTable like this:
txtopd_charges.Text = dt.Rows[0]["amount"].ToString();
txtdr_charges.Text = dt.Rows[0]["registration_charges"].ToString();
UPDATED
You can bind the data with Repeater and initialized your textbox inside of the ItemTemplate which will repeat your data exist in DataTable.
Aspx Code
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:TextBox ID="txtopd_charges" Text='<%# Eval("amount") %>' runat="server"></asp:TextBox>
<asp:TextBox ID="txtdr_charges" Text='<%# Eval("registration_charges") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
and in your C#
if (dt.Rows.Count > 0)
{
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
Related
I currently have two dropdown lists and they are populated with names from a database. What I want to do is have a player be selected, and then on a button click, the data from the table is populated into a gridview. Right now I am just getting a "No data returned" message and I cannot figure out why.
<asp:DropDownList ID="ddl_QB1" runat="server" Width="200px" AppendDataBoundItems="True"
AutoPostBack="True" Height="16px" DataTextField="Player" DataValueField="id" ></asp:DropDownList>
<asp:Gridview ID="GridView1" runat="server" AutoGenerateColumns="false" Visible="true"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px"
CellPadding="4" GridLines="Horizontal" ShowHeaderWhenEmpty="True" EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Total Points">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("[Pts]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Pts") %>'>
</asp:Label>
</ItemTemplate>
protected void Page_Load(object sender, EventArgs e)
{
LoadQuarterbacks();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] from Quarterbacks", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddl_QB1.DataSource = dt;
ddl_QB1.DataBind();
}
}
private void LoadQuarterbacks()
{
ddl_QB1.Items.Clear();
ddl_QB2.Items.Clear();
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("SELECT id, Player FROM Quarterbacks", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("Quarterbacks");
da.Fill(ds); // fill dataset
ddl_QB1.DataTextField = ds.Tables[0].Columns["Player"].ToString(); // text field name of table dispalyed in dropdown
ddl_QB2.DataTextField = ds.Tables[0].Columns["Player"].ToString();
ddl_QB1.DataValueField = ds.Tables[0].Columns["id"].ToString();
ddl_QB2.DataValueField = ds.Tables[0].Columns["id"].ToString(); // to retrive specific textfield name
ddl_QB1.DataSource = ds.Tables[0];
ddl_QB2.DataSource = ds.Tables[0];
ddl_QB2.DataBind();//assigning datasource to the dropdownlist
ddl_QB1.DataBind(); //binding dropdownlist
con.Close();
ddl_QB1.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
ddl_QB2.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionstring);
string query = "SELECT [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] FROM Quarterbacks where id=" + ddl_QB1.SelectedValue;
SqlDataAdapter sda = new SqlDataAdapter(query,con);
con.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Following 3 changes would give desired results.
First - AutoPostBack should be set to false on the dropdown element as that is causing postback even before you click on the button.
Second - remove the current code inside if(!Page.IsPostback). This code is not necessary. Also, this code is not setting DataTextField and DataValueField properties for ddl_QB1 and ddl_QB2.
Third - put the method call LoadQuarterbacks() inside if(!Page.IsPostback). We do not have to bind these values for ddl_QB1 and ddl_QB2 on each request.
If a refresh is required on the dropdown controls, then call LoadQuarterbacks() method after binding the gridview at the end of the button click. That way you are capturing the selected values from dropdown before rebinding the them. Rebinding the DropDowns would cause them loose the selected values.
I have a GridView which gets the data from a SQL Server database.
The GridView binds when the user select the date from an CalendarExtender, because the data is different one day to another, also the rows quantity.
E. G., in Saturdays the GridView is filled with 18 rows. In Tuesdays, with 58.
Concern:
What I need to do is to split the GridView in 2 parts (2 GridViews). E. G., In tuesdays, 29 rows each GridView, in saturdays, 9 rows each.
I have tried:
To bring the daily data into a GridView, called "GVTotal":
if (Weekday.Value == "Saturday")
{
GVTotal.DataSourceID = SaturdayData.ID;
GVTotal.DataBind();
}
To count the rows from GVTotal, and divide by 2.
int everything = GVTotal.Rows.Count;
int half = everything / 2;
What I want to do now, is to "Copy" the rows from 0 to half to GVPart1, and from half to everything to GVPart2, in the exactly same order than in GVTotal.
I have read that maybe using a DataTable will made this possible.
I am not pretty sure how to do that. Could someone help me please?
You could have a Repeater with two items, one for each GridView. In the example below, the Repeater is rendered as a table with a single row. Each GridView is in a cell of that row, with an empty cell between them.
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="0" cellpadding="0">
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" >
...
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 32px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
In order to get the two data sources, you declare two DataTables in your class:
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
In Page_Load, the two DataTables are populated by splitting the full DataTable in two parts, and the data source of the Repeater is set to two boolean values:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection("Data Source=(local); Integrated Security = True; Initial Catalog=TestMP"))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Clients ORDER BY ClientID ASC", conn))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
The specific data source can then be set for each GridView in the ItemDataBound event handler of the Repeater:
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bool isTopHalf = (bool)e.Item.DataItem;
GridView gvHalf = e.Item.FindControl("gvHalf") as GridView;
gvHalf.DataSource = isTopHalf ? dtTopHalf : dtBottomHalf;
gvHalf.DataBind();
}
}
Note 1: The Repeater allows to share the same markup for both GridViews. If you prefer, you can declare two separate GridViews in the markup and apply the specific data source to each one in Page_Load.
Note 2: You need a reference to System.Data.DataSetExtensions in your project to use some of the LINQ methods mentioned above.
Thanks to ConnorsFan for the assistance. His answer is the right way to do what I wanted.
As I need to select the date before the data comes in, I wrote Connor's code into my date Textbox OnTextChanged event, into the if (Weekday.Value == "<day of the week>") statement.
This is the solution:
ASPX:
Updated: Only with one GridView, as reccomended:
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="200px" cellpadding="0">
<tr style="vertical-align: top;">
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" BackColor="White" AutoGenerateColumns="False" HeaderStyle-CssClass="tituloshandoff" RowStyle-CssClass="contenidohandoffbatch">
<Columns>
<asp:BoundField HeaderText="IDBATCH" DataField="IDBatch" SortExpression="IDBatch" HeaderStyle-CssClass="TituloInvisible" ItemStyle-CssClass="TituloInvisible" />
<asp:BoundField HeaderText="BATCH" DataField="Nombre" SortExpression="Nombre" />
<asp:BoundField HeaderText="DEALER" DataField="DealerCodigo" SortExpression="DealerCodigo" />
<asp:BoundField HeaderText="CT TIME" DataField="CTStart" SortExpression="CTStart" />
<asp:BoundField HeaderText="STATUS" DataField="Estado" SortExpression="Estado" />
<asp:TemplateField HeaderText="CONTROL">
<ItemTemplate>
<asp:Button ID="Button1" CssClass="botongrid" runat="server" Text="Select" Width="100px" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 100px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
C#:
I will show only one day in example:
string LaConexion = #"<My Connection String>";
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
protected void TextDate_TextChanged(object sender, EventArgs e)
{
if (diasemana.Value == "Monday")
{
using (SqlConnection conexion = new SqlConnection(LaConexion))
using (SqlCommand comando = new SqlCommand("SELECT [1Monday].IDBatch, Batch.Nombre, Dealer.DealerCodigo, Batch.CTStart, BatchDatos.Estado FROM [1Monday] INNER JOIN Batch ON [1Monday].IDBatch = Batch.IDBatch INNER JOIN Dealer ON Batch.IDDealer = Dealer.IDDealer LEFT OUTER JOIN BatchDatos ON [1Monday].ID = BatchDatos.ID ORDER BY Batch.CTStart", conexion))
{
comando.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(comando);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
A Picture:
I am trying to get the StudentFirstName from data base and show in the text box right now am using grid view where it shows the data but not in textbox am not sure how to get all the data from data base and show in individual text box.
MyDB
StudentFirstName SchoolID StudCourse
abc sc123 A
cef sc155 A
gij sc133 A
abc sc122 B
cef sc156 B
gij sc144 B
C#
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select StudentFirstName from student WHERE StudCourse=#DDSelected_Class order by StudentFirstName ASC";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#DDSelected_Class", DDSelected_Class);
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader == null || !oReader.HasRows)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);
}
else
{
while (oReader.Read())
{
GridView1.DataSource = oReader;
GridView1.DataBind();
}
}
myConnection.Close();
}
}
Gridview
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
You will need to define ItemTemplate for your column. It will contain a textbox and the field name name in Eval to bind it.
Complete code sample:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("StudentFirstName ") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<Columns>
</asp:GridView>
I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!
I have a gridview which contains textboxes and dropdowns.In gvScheduleBattingScore_RowDataBound Event I am binding dropdowns without any problem. The button control is outside to the gridview. I actually want to submit all the textbox values and dropdown selected values to the database on buttonclickevent But I don't know where I am going wrong.
The Problem is Textboxes do not contain any text and am getting Exception
Input string was not in a correct format.
Please help me out...
<asp:GridView ID="gvScheduleBattingScore" runat="server" AllowSorting="false" AutoGenerateColumns="False" AllowPaging="false"
GridLines="None" CellPadding="1" CssClass="GridViewStyle" ShowFooter="false" width="100%"
OnRowDataBound="gvScheduleBattingScore_RowDataBound">
<Columns>
<asp:BoundField DataField="P_PlayerId" HeaderText="Player Id" HeaderStyle-Wrap="true" HeaderStyle-Width="5%" Visible="false"/>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" HeaderStyle-Wrap="true" HeaderStyle-Width="30%"/>
<asp:TemplateField HeaderText="Playing Order" HeaderStyle-Wrap="true" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtPlayingOrder" runat="server" CssClass="TinyTexBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bold By">
<ItemTemplate>
<asp:DropDownList ID="ddlBoldBy" runat="server"> </asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</br>
<asp:Button ID="ButtonAdd" runat="server" Text="Add" CssClass="SmallButton"
ValidationGroup="Add" onclick="ButtonAdd_Click"/>
On ButtonClick Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlConnection dBConnection = null;
try
{
int playerId;
short plyerOrder;
string BatsmanStatus;
int boldBy;
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["CriConn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_InsertScores", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow GVRow in gvScheduleBattingScore.Rows)
{
string textPlayerId = GVRow.Cells[0].Text;
TextBox textPlyerOrder = (TextBox)GVRow.Cells[1].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = GVRow.Cells[2].FindControl("txtStatus") as TextBox;
DropDownList DropDownBoldBy = (DropDownList)GVRow.Cells[18].FindControl("ddlBoldBy");
playerId = Convert.ToInt32(textPlayerId );
if (!string.IsNullOrEmpty(textPlyerOrder.Text))
plyerOrder = Convert.ToInt16(textPlyerOrder.Text);
if (!string.IsNullOrEmpty(textBatsmanStatus.Text))
BatsmanStatus = textBatsmanStatus.Text;
if (!string.IsNullOrEmpty(DropDownBoldBy.SelectedValue) && DropDownLbwBy.SelectedValue != "Select")
boldBy = Convert.ToInt32(DropDownBoldBy.SelectedValue);
cmd.Parameters.Add("#PlayerId", SqlDbType.NVarChar).Value = playerId;
cmd.Parameters.Add("#PlayerId", SqlDbType.Int).Value = playerId;
cmd.Parameters.Add("#plyerOrder", SqlDbType.Int).Value = plyerOrder;
cmd.Parameters.Add("#BatsmanStatus", SqlDbType.NVarChar).Value = BatsmanStatus;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
cmd.ExecuteNonQuery();
dBConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
As per the Chat discussion with #bhoopendra.sahoo, we come to the conclusion that it is a Binding issue.
When Button Click Event is fired, the GridView binds again causing the issue.
The fix is to bind the GridView only once and restrict its binding during other events.
Add a null checking before converting the textbox value to int
if (!string.IsNullOrEmpty(textPlayerId.Text))
playerId = Convert.ToInt32(textPlayerId);
Also make these changes to you code, to find the textbox controls in the correct cell
TextBox textPlyerOrder = (TextBox)GVRow.Cells[2].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = (TextBox)GVRow.Cells[3].FindControl("txtStatus");